如何从内容中为元素设置属性?

时间:2018-03-22 14:07:19

标签: javascript jquery html

我想添加带有元素.double-text属性data-content的所有元素以及元素的内容值。

我尝试了类似的东西

$(function(){
  $('.text-double').attr("data-content", $(this).text());
});

但是,显然,它不起作用。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

您需要使用$.each

$('.text-double').each(function(){$(this).attr("data-content", $(this).text();});

答案 1 :(得分:1)

您可以使用$.each()

功能



$(function() {
  $('.text-double').each(function() {
    $(this).attr("data-content", $(this).text());
    console.log(this);
  })
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="text-double">Ele</p>
<p class="text-double">from</p>
<p class="text-double">SO</p>
&#13;
&#13;
&#13;