如何使用jQuery的Javascript交换div中的文本链接?

The*_*leA 1 html javascript jquery indexof

我想转为以下html:

<div id="myText">Another hurricane is coming <a data-number="23">here</a>. And check out pictures <a data-number="43">here</a>.</div>
Run Code Online (Sandbox Code Playgroud)

进入这个:

<div id="myText">Another hurricane is coming @[23]. And check out pictures @[43].</div>
Run Code Online (Sandbox Code Playgroud)

我基本上试图获取每个"数据编号"值并将其放入方括号中,同时省略a-tags中的文本.

有关如何最好地解决这个问题的想法吗?

Ant*_*ton 7

您可以使用 .replaceWith()

$('#myText').find('a').replaceWith(function(){
       return "@["+ $(this).data('number')+"]";
});
Run Code Online (Sandbox Code Playgroud)

DEMO

您可以.find('a[data-number]')像评论中指出的@ColinDeClue一样使用,以确保获得具有该属性的锚点data-number.

  • 可能想要在选择器中添加一个`[data-number]`,以防万一有其他锚标签. (2认同)