Jquery:如何在一串文本中找到单独的数字集并为其添加 href 标签

Jquery: How to find individual sets of numbers in a string of text and add href tags to them

我有几个带有数字的文本字符串,用于连接到索引中的其他条目(使用散列,因为它们将一起出现在一个页面上)。例如:

<div class="description"><span>This is some text, which we will reference in entry (330) and also in entry (249).</span></div>

我已经能够让数字显示出来,用逗号分隔,但我无法让它们在添加链接时分开,实际上我不完全确定如何我应该着手用 href 包装它们而不替换它们周围的文本。这是我目前所处的位置,但我碰壁了。

        var val = $("description span").html();
        var numbers = val.match(/\d+/g);
        if (numbers != null) {
           console.log(numbers);
          //here goes the separate and wrap code that eludes me.
        }

预期结果:

<div class="description"><span>This is some text, which we will reference in entry (<a href="myindex.html#330">330</a>) and also in entry (<a href="myindex.html#249">249</a>).</span></div>

感谢您的帮助。

如评论中所述,您的选择器中缺少 .,除此之外您可以尝试类似的操作:

$.each(numbers, function(n, t) {
  $(".description span").html($(".description span").html().replace(t, "<a href='#" + t + "'>" + t + "</a>"))
})

演示

var val = $(".description span").html();
var numbers = val.match(/\d+/g);
if (numbers != null) {
  $.each(numbers, function(n, t) {
    $(".description span").html($(".description span").html().replace(t, "<a href='#" + t + "'>" + t + "</a>"))
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="description"><span>This is some text, which we will reference in entry (330) and also in entry (249).</span></div>