我想在我的整个html文档中更改所有属性的名称,其中class="testingCase"
。
例如,更改:
<a class="testingCase" href="#" title="name of testing case">Blabla</a>
<a class="testingCase" href="#" title="name of another testing case">Bloo</a>
要这样做:
<a class="testingCase" href="#" newTitleName="name of testing case">Blabla</a>`
<a class="testingCase" href="#" newTitleName="name of another testing case">Bloo</a>`
我正在考虑一个查找和替换,但对于如此简单的东西,这似乎有很多代码。有没有针对这个的jQuery函数或者一个简单的方法?
发布于 2008-11-25 12:31:48
在javascript中没有内置的方法/函数来“重命名”属性,但是您可以创建新的属性并删除其他属性……
$('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>
编辑:增加了只选择class=为“testingCase”的a
元素的功能。
发布于 2013-07-19 22:49:22
稍晚一点,但是这个link有一个很棒的jquery函数扩展:
jQuery.fn.extend({
renameAttr: function( name, newName, removeData ) {
var val;
return this.each(function() {
val = jQuery.attr( this, name );
jQuery.attr( this, newName, val );
jQuery.removeAttr( this, name );
// remove original data
if (removeData !== false){
jQuery.removeData( this, name.replace('data-','') );
}
});
}
});
示例
// $(selector).renameAttr(original-attr, new-attr, removeData);
// removeData flag is true by default
$('#test').renameAttr('data-test', 'data-new' );
// removeData flag set to false will not remove the
// .data("test") value
$('#test').renameAttr('data-test', 'data-new', false );
这不是我写的。但我测试的是JQ 1.10。代码来自链接。
发布于 2013-05-25 22:55:45
下面是一个简单的jquery风格的插件,它提供了一个renameAttr方法:
// Rename an entity attribute
jQuery.fn.renameAttr = function(oldName, newName) {
var args = arguments[0] || {};
var o = $(this[0])
o
.attr(
newName, o.attr(oldName)
)
.removeAttr(oldName)
;
};
还有一个this example,它添加了一个删除旧属性数据的选项。
https://stackoverflow.com/questions/317170
复制相似问题