
本文档将介绍如何使用 JavaScript 查找具有特定属性值的 HTML 元素,并动态地修改其 CSS 类名。我们将通过一个实际示例,演示如何根据按钮点击事件传递的 ID 值,查找具有相应 `data-dselect-value` 属性的元素,并为其添加 `active` 类。
JavaScript 提供了多种方法来查找 HTML 元素,其中 document.querySelector 方法是最灵活和常用的方法之一。它允许我们使用 CSS 选择器来查找元素。
在我们的示例中,我们需要查找 data-dselect-value 属性值等于按钮点击事件传递的 ID 值的元素。我们可以使用属性选择器 [attribute="value"] 来实现。
以下是实现该功能的 JavaScript 代码:
立即学习“Java免费学习笔记(深入)”;
function myFunc(clicked_id){
var elem = document.querySelector('[data-dselect-value="'+clicked_id+'"]');
elem.classList.add('active');
};代码解释:
为了更好地理解上述代码,我们提供一个 HTML 示例:
<div class="dropdown-menu">
<div class="d-flex flex-column">
<input onkeydown="return event.key !== 'Enter'" onkeyup="dselectSearch(event, this, 'dselect-wrapper', 'form-select', false)" type="text" class="form-control" placeholder="Search" autofocus="">
<div class="dselect-items" style="max-height:360px;overflow:auto">
<button class="dropdown-item active" data-dselect-value="1109" type="button" onclick="dselectUpdate(this, 'dselect-wrapper', 'form-select')">Charles</button>
<button class="dropdown-item" data-dselect-value="1108" type="button" onclick="dselectUpdate(this, 'dselect-wrapper', 'form-select')">Fred</button>
<button class="dropdown-item" data-dselect-value="1107" type="button" onclick="dselectUpdate(this, 'dselect-wrapper', 'form-select')">Lionel</button>
<button class="dropdown-item" data-dselect-value="1106" type="button" onclick="dselectUpdate(this, 'dselect-wrapper', 'form-select')">Robert</button>
<button class="dropdown-item" data-dselect-value="1105" type="button" onclick="dselectUpdate(this, 'dselect-wrapper', 'form-select')">Mike</button>
</div>
<div class="dselect-no-results d-none">No results found</div>
</div>
</div>
<button onclick="myFunc(this.id)" id="1106">Select client</button>在这个例子中,当点击 ID 为 "1106" 的按钮时,myFunc 函数会被调用,并将 "1106" 作为 clicked_id 传递给函数。 document.querySelector 将查找 data-dselect-value 属性值为 "1106" 的按钮元素,并为其添加 active 类。
本文介绍了如何使用 JavaScript 根据属性值查找 HTML 元素,并动态地修改其 CSS 类名。 document.querySelector 方法是一个强大的工具,可以帮助我们轻松地查找和操作 HTML 元素。 理解并掌握这些技术,可以帮助我们构建更加动态和交互性强的 Web 应用程序。
以上就是JavaScript:根据属性值查找元素并修改其类名的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号