change data-attribute using jquery

霸气de小男生 提交于 2020-02-02 06:04:43

问题


How can I change

<div data-300=""></div>

to

<div data-500=""></div>

using jquery?

I don't want to remove the attribute and replace it as it contains data I need I just need to change the '300' to '500'.


回答1:


Not generic at all, but it should do the job

var $target = $('div[data-300]'),
    oldData = $target.data('300');

$target.removeAttr('data-300').attr({ 'data-500': oldData });



回答2:


Here's a function you can use:

function attrChangeName(elem, attr, new_attr) {
  var data = $(elem).attr(attr);
  $(elem).attr(new_attr, data);
  $(elem).removeAttr(attr);
}


来源:https://stackoverflow.com/questions/18751450/change-data-attribute-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!