我想class="testingCase"在整个html文档中更改所有属性的名称.
例如:变化:
<a class="testingCase" href="#" title="name of testing case">Blabla</a>
<a class="testingCase" href="#" title="name of another testing case">Bloo</a>
Run Code Online (Sandbox Code Playgroud)
对此:
<a class="testingCase" href="#" newTitleName="name of testing case">Blabla</a>`
<a class="testingCase" href="#" newTitleName="name of another testing case">Bloo</a>`
Run Code Online (Sandbox Code Playgroud)
我在想一个查找和替换,但似乎很多代码很容易.这个或简单方法有jQuery函数吗?
nic*_*ckf 38
我不认为你可以"重命名"一个属性,但是你可以创建新属性并删除其他属性......
$('a.testingCase[title]').each(function() {
var $t = $(this);
$t.attr({
newTitleName: $t.attr('title'),
})
.removeAttr('title');
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
编辑:添加在使其仅选择a元素的位中class="testingCase"
我认为您不能更改属性名称,但您可以做的是:
<a>具有title属性的所有标记;JQuery允许你以这种方式使用内置函数:
/* get all <a> with a "title" attribute that are testingCase
then apply an anonymous function on each of them */
$('a.testingCase[title]').each(function() {
/* create a jquery object from the <a> DOM object */
var $a_with_title = $(this);
/* add the new attribute with the title value */
$a_with_title.attr("newTitleName", $a_with_title.getAttribute('title'));
/* remove the old attribute */
$a_with_title.removeAttr('title');
});
Run Code Online (Sandbox Code Playgroud)
稍后,但这个链接有一个很棒的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-','') );
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
例
// $(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 );
Run Code Online (Sandbox Code Playgroud)
我不写这个.但我测试的是JQ 1.10.该代码来自链接.
| 归档时间: |
|
| 查看次数: |
32349 次 |
| 最近记录: |