如何获取由 JQuery.data() 创建的具有特定数据属性的元素?
How to get element with specific data attribute which created by JQuery.data()?
我知道 JQuery 已经有 select 具有数据属性的元素的方法,看起来像
$("[data-attr='value']")
但是,如果您使用 JQuery.data() 方法将数据放入 HTML 元素,例如
$("button").data("attrName", "attrValue");
而不是
$("button").attr("attrName", "attrValue");
你不会真正得到
<button data-attrName="attrValue"> </button>
因此,您不能使用
$("button[data-attrName='attrValue']")
获取此按钮。
如题。
有什么方法可以 select 具有由 JQuery.data() 创建的具有特定数据属性的元素?
如果 data
属性是通过 jQuery 的 data()
方法添加的,那么它在 DOM 中将不可用,因此属性选择器将不起作用- 如您所见。
另一种方法是使用 filter()
,像这样:
var $button = $('button').filter(function() {
return $(this).data('attrName') == 'attrValue';
});
我知道 JQuery 已经有 select 具有数据属性的元素的方法,看起来像
$("[data-attr='value']")
但是,如果您使用 JQuery.data() 方法将数据放入 HTML 元素,例如
$("button").data("attrName", "attrValue");
而不是
$("button").attr("attrName", "attrValue");
你不会真正得到
<button data-attrName="attrValue"> </button>
因此,您不能使用
$("button[data-attrName='attrValue']")
获取此按钮。
如题。 有什么方法可以 select 具有由 JQuery.data() 创建的具有特定数据属性的元素?
如果 data
属性是通过 jQuery 的 data()
方法添加的,那么它在 DOM 中将不可用,因此属性选择器将不起作用- 如您所见。
另一种方法是使用 filter()
,像这样:
var $button = $('button').filter(function() {
return $(this).data('attrName') == 'attrValue';
});