javascript - 根据数据属性搜索html元素

标签 javascript jquery

有没有办法根据数据属性搜索元素?

我有以下代码,想知道如何实现

<UL>
    <LI data-relation_id=1/>
    <LI data-relation_id=1/>
    <LI data-relation_id=1/>
    <LI data-relation_id=2/>
    <LI data-relation_id=2/>
    <LI data-relation_id=2/>
    <LI data-relation_id=3/>
    <LI data-relation_id=3/>
    <LI data-relation_id=3/>
</UL>

在点击事件中,我基本上想找出属于特定数据关系的所有项目?

function getRelatedObjects(relationId){
   //Search all the li's and get the LI 
   //that have the data-relation_id== relationId

}

这可以使用 jquery 完成吗?

最佳答案

data属性只是一个属性,所以可以使用属性选择器。

$('li[data-relation_id='+relationId+']')

关于javascript - 根据数据属性搜索html元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7156570/

相关文章:

javascript - Chrome 在调用日志时无法识别 console.log

javascript - 为什么悬停对 child 不起作用,而是对 parent 起作用​​?

javascript - CSS动画帮助。仅以一种方式播放

javascript - 类型错误 : Cannot read property 'publish' of undefined in (ReactJS)

javascript - jQuery添加<li>元素后触发函数?

javascript - 从 Bootstrap 3 删除模式将行 ID 传递给 Laravel Controller

php - 对 PHP 的 Ajax 调用仅返回 "status 200 OK"但没有包含数据库结果的数组?

javascript - append.html jquery 与现有 html 的工作方式不同吗?

javascript - 如何检测TraceMonkey?

javascript - 从 Microsoft Graph API(测试版)通信 API 获取实时更新