在Jquery中获取目标元素的属性

时间:2015-03-12 09:28:22

标签: javascript jquery

我希望将带有class data-item的所有div替换为具有此类的item的属性data-variable

IE:

<div class="data-item" data-variable="{{somevariable}}">
  Some Content
</div> 

<div class="data-item" data-variable="{{someothervariable}}">
  Some Content
</div> 

应该成为

{{somevariable}}{{someothervariable}}

我想使用的代码:

$( "div.data-item" , el ).replaceWith( get the data-variable attribute of this element);

其中el是包含我要解析的html的jquery对象

2 个答案:

答案 0 :(得分:1)

replaceWith的参数可以是一个函数。当它被调用时,this将是被替换的元素。返回值将用作替换值。

$("div.data-item").replaceWith(function() {
    return $(this).attr("data-variable");
});

答案 1 :(得分:0)

DEMO

$( "div.data-item").each(function(){
  $(this).replaceWith($(this).data('variable'));
})

UPD:您可以将函数用作replaceWith的参数(thx @Barmar)

$('div.data-item').replaceWith(function() {
    return $(this).data('variable');
});
相关问题