如何使用jQuery更改HTML属性名称? [英] How can I change HTML attribute names with jQuery?
本文介绍了如何使用jQuery更改HTML属性名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在整个html文档中更改 class =testingCase
的所有属性名称。
例如更改:
< a class =testingCasehref =#title =测试用例名称> Blabla< ; / A>
< a class =testingCasehref =#title =另一个测试用例的名称> Bloo< / a>
至此:
< a class =testingCasehref =#newTitleName =测试用例名称> Blabla< / a>`
< a class =testingCasehref = #newTitleName =另一个测试用例的名称> Bloo< / a>`
想到一个发现和替换,但似乎很多代码很容易。有没有这个或一个简单的方法的jQuery函数?
解决方案
我不认为你可以重命名一个属性,但您可以创建新的属性并删除其他属性...
$( 'a.testingCase [title]')。each(function(){var $ t = $(this); $ t.attr({newTitleName:$ t.attr('title'),}).removeAttr('title ');});
< script src = https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script><a class =testingCasehref =#title =name测试用例>> Blabla< / a>< a class =testingCasehref =#title =另一个测试用例的名称> Bloo< / a>
$ 编辑:在位添加了ma kes仅选择 a
元素与 class =testingCase
I would like to change all the names of the attributes where class="testingCase"
throughout all my whole html document.
e.g. Change:
<a class="testingCase" href="#" title="name of testing case">Blabla</a>
<a class="testingCase" href="#" title="name of another testing case">Bloo</a>
To this:
<a class="testingCase" href="#" newTitleName="name of testing case">Blabla</a>`
<a class="testingCase" href="#" newTitleName="name of another testing case">Bloo</a>`
I was thinking of a find and replace but that seems a lot of code for something so easy. Is there a jQuery function for this or a simple method?
解决方案
I don't think you can "rename" an attribute, but you can create new attributes and remove other ones...
$('a.testingCase[title]').each(function() {
var $t = $(this);
$t.attr({
newTitleName: $t.attr('title'),
})
.removeAttr('title');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="testingCase" href="#" title="name of testing case">Blabla</a>
<a class="testingCase" href="#" title="name of another testing case">Bloo</a>
Edit: added in the bit that makes it only select a
elements with class="testingCase"
这篇关于如何使用jQuery更改HTML属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文