Javascript jQuery-为每个元素获取标记文本并输出它

Javascript jQuery-为每个元素获取标记文本并输出它,javascript,jquery,html,Javascript,Jquery,Html,输入HTML <h2>A random title</h2> <h3>Another cool title</h3> 结果我得到: <h2 class="ghost" data-titre="A random title Another cool title">A random title</h2> <h3 class="ghost" data-titre="A random title Another cool t

输入HTML

<h2>A random title</h2>
<h3>Another cool title</h3>
结果我得到:

<h2 class="ghost" data-titre="A random title Another cool title">A random title</h2>
<h3 class="ghost" data-titre="A random title Another cool title">Another cool title</h3>
随机标题
另一个很酷的标题

您只需设置类,然后使用带有回调的
attr

$('h2,h3').addClass('ghost').attr('data-titre',function(){
返回$(this.text())
});
console.log(document.body.innerHTML)

随意的头衔

另一个很酷的标题
您只需设置类,然后使用带有回调的
attr

$('h2,h3').addClass('ghost').attr('data-titre',function(){
返回$(this.text())
});
console.log(document.body.innerHTML)

随意的头衔

另一个很酷的标题
通过每个元素循环添加文本和类

var ghost = $('h2, h3');
ghost.each(function() {
 $( this ).attr('data-titre',$(this).text());
 $( this ).addClass('ghost');
});

循环遍历每个元素以添加文本和类

var ghost = $('h2, h3');
ghost.each(function() {
 $( this ).attr('data-titre',$(this).text());
 $( this ).addClass('ghost');
});

您可以循环使用
ghost
,这样就不会覆盖值。您可以循环使用
ghost
这样就不会覆盖值。非常好,谢谢。我从来没有想过使用回调!很好用,不用那么多台词,谢谢。我从来没有想过使用回调!
var ghost = $('h2, h3');
ghost.each(function() {
 $( this ).attr('data-titre',$(this).text());
 $( this ).addClass('ghost');
});