javascript - 在 jQuery 中使用数据属性对象作为选择器

标签 javascript jquery custom-data-attribute

我有以下数据属性对象:

<div data-vp="{
      id: "vp-485858383",
      customTwo: "test"
}">
</div>

我正在尝试使用 jQuery 中的特定 id 值定位 data-vp:

$(['data-vp with id:vp-485858383'].parent().find('.fa.fa-times').show();

我这样做是为了仅显示 .fa.fa-times 的特定实例,而不是所有具有 .fa.fa-times 类的元素。

我知道上面的选择器显然不会起作用,但是是否可以将 data-vp 与特定 ID 一起定位?

最佳答案

您可以为此使用属性包含选择器:

$(function() {
  $('[data-vp*="id: vp-485858383"]').css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-vp='{
      id: vp-485858383,
      customTwo: "test"
}'>
asdf
</div>

Note that your text must be exactly the same.

另一种选择是根据 data-vp 属性过滤元素:

$(function() {
  $('[data-vp]').filter(function(i, el) {
    return $(el).data('vp').id == 'vp-485858383';
  }).css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-vp='{
      "id": "vp-485858383",
      "customTwo": "test"
}'>
asdf
</div>
<div data-vp='{
      "id": "vp-123",
      "customTwo": "test"
}'>
asdf
</div>

For that you must have the content of the data-vp attribute to be a valid json string.

关于javascript - 在 jQuery 中使用数据属性对象作为选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44123826/

相关文章:

javascript - 替换隐藏/显示上的链接文本

javascript - 如何在 JavaScript 中格式化数字?

javascript - 从 Vue 应用程序外部访问 Vue 方法或事件

javascript - 使用数据属性和点击功能将数据值推送到 div

jquery - 使用 HTML5 数据属性作为变量,而不是字符串

javascript - 我可以使用 jquery 字符串来定位 id 吗?

javascript - 在日历上画一条线

jquery - 使用 HR 标签调整文本区域的大小

javascript - jquery- 改变 css 但不能重置为 original-fadein() 导致程序也停止工作

jquery - Application.js 放置 - Rails 3 和 jQuery