jQuery循环查找数据属性并将它们分别编号为不同的数字
嘿,我正在尝试查找所有数据属性,并用数字计数替换名称 示例HTML如下所示:jQuery循环查找数据属性并将它们分别编号为不同的数字,jquery,custom-data-attribute,Jquery,Custom Data Attribute,嘿,我正在尝试查找所有数据属性,并用数字计数替换名称 示例HTML如下所示: <li class="ui-menu-item" role="presentation" data-name="0"> <a id="ui-id-2" class="ui-corner-all" tabindex="-1">AScript</a> </li> <li class="ui-menu-item" role="presentation" data-n
<li class="ui-menu-item" role="presentation" data-name="0">
<a id="ui-id-2" class="ui-corner-all" tabindex="-1">AScript</a>
</li>
<li class="ui-menu-item" role="presentation" data-name="0">
<a id="ui-id-2" class="ui-corner-all" tabindex="-1">Something</a>
</li>
etc etc...
AScript
某物
等等等等。。。
大约有20个具有相同的数据名属性。我想在页面中循环,找到该属性,然后替换该数字并添加正确的数字
例如:
<li class="ui-menu-item" role="presentation" data-name="0">
<a id="ui-id-2" class="ui-corner-all" tabindex="-1">AScript</a>
</li>
<li class="ui-menu-item" role="presentation" data-name="1">
<a id="ui-id-2" class="ui-corner-all" tabindex="-1">Something</a>
</li>
<li class="ui-menu-item" role="presentation" data-name="2">
<a id="ui-id-2" class="ui-corner-all" tabindex="-1">Hey there</a>
</li>
etc etc...
AScript
某物
嘿
等等等等。。。
请注意,数据名如何为0、1、2等
这就是我想要做的。使用jQuery是否可以这样做?您可以循环使用具有特定属性的任何元素,然后更改该元素,如下面的示例所示:
$('[data-name]').each(function (e) {
// Set the data-name to the item number
$(this).attr('data-name', e);
// Print the new `data-name` to the console
console.log($(this).attr('data-name'));
});
JSFiddle:
注意:看看这篇文章,决定使用attr
或数据
:
您可以循环通过具有特定属性的任何元素,然后更改该元素,如以下示例所示:
$('[data-name]').each(function (e) {
// Set the data-name to the item number
$(this).attr('data-name', e);
// Print the new `data-name` to the console
console.log($(this).attr('data-name'));
});
JSFiddle:
注意:看看这篇文章,决定使用attr
或数据
:
类似于:
$("[data-name=0]").each(function(i) {
$(this).data("name", i);
});
比如:
$("[data-name=0]").each(function(i) {
$(this).data("name", i);
});
首先选择所有具有名为数据名属性的li标记,并使用循环更改其值
$('li[data-name]').each(function(i) {
$(this).attr('data-name', i);
});
已编辑:以为您只想在属性的末尾添加一个数字。首先选择所有具有名为“数据名”属性的li标记,并使用循环更改其值
$('li[data-name]').each(function(i) {
$(this).attr('data-name', i);
});
已编辑:我以为您只想在属性的末尾添加一个数字。我认为这行不通。所有数据名都以“0”开头。我需要为它找到的每一个更改为一个唯一的数字。啊,在这种情况下,您可以替换
$(this.attr('data-name',$(this.attr('data-name')+'N')代码>行与$(this).attr('data-name',e)代码>。编辑了我原来的帖子。我认为那不管用。所有数据名都以“0”开头。我需要为它找到的每一个更改为一个唯一的数字。啊,在这种情况下,您可以替换$(this.attr('data-name',$(this.attr('data-name')+'N')代码>行与$(this).attr('data-name',e)代码>。编辑了我原来的帖子。