首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用jQuery更改HTML属性名称?

如何使用jQuery更改HTML属性名称?
EN

Stack Overflow用户
提问于 2008-11-25 12:28:08
回答 6查看 39.6K关注 0票数 24

我想在我的整个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函数或者一个简单的方法?

EN

回答 6

Stack Overflow用户

发布于 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元素的功能。

票数 46
EN

Stack Overflow用户

发布于 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。代码来自链接。

票数 7
EN

Stack Overflow用户

发布于 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,它添加了一个删除旧属性数据的选项。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/317170

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档