【问题标题】:How to change the attribute using jquery? [duplicate]如何使用jquery更改属性? [复制]
【发布时间】:2016-05-11 09:22:40
【问题描述】:

我有这个标签

<div data-type="move" >some text</div>

如何更改属性以使其成为

<div data-ty="move" >some text</div>

【问题讨论】:

标签: javascript jquery


【解决方案1】:

删除现有属性并添加新属性

$('[data-type]').each(function() { // get all elemnts which have the attribute `data-type` and iterate over them
  var temp = $(this).data('type'); // get the existing element attribute value
  $(this)
    .removeAttr('data-type') // remove the attribute
    .attr('data-ty', temp); // add new attribute with value of existing
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-type="move">some text</div>

【讨论】:

    【解决方案2】:

    只有两行:

    <div class="myDiv" data-type="move" >some text</div>
    
    $('.myDiv').removeAttr('data-type'); // first remove old attribute
    $('.myDiv').attr('data-ty',"move"); // now add new attribute
    

    【讨论】:

    • 这会将data-ty 属性添加到页面上的每个div。
    • 因为 OP 没有提到 div 中的任何类..它会给出答案..但是为了他的参考,他也可以将类添加到该 div 并使用它的类,他可以将属性添加到 div
    猜你喜欢
    • 2019-01-16
    • 1970-01-01
    • 2012-08-11
    • 2020-06-15
    • 1970-01-01
    • 2012-05-26
    • 2010-11-22
    • 2017-11-17
    • 2012-06-19
    相关资源
    最近更新 更多