猿问

如何使用 JavaScript 突出显示包含数组中关键字的所有链接

我正在网页中搜索数组中的关键字。此代码通过将文本替换为突出显示文本的标签来工作,但是当它找到作为链接的关键字时,它会破坏它们,因为它在标签中放置了一个<span>标签<a>。


我试图通过将 $this.html() 更改为 $this.parent.html() 来引用父元素,但这不起作用。这是 JSFiddle:https ://jsfiddle.net/uzfsjqyr/1/


我会很感激一些帮助,好吗?


var regex = /(Apples|oranges)/g;

$('*').each(function() {

    var $this = $(this);

    var text = $this.text();

    if (regex.test(text)) {

        $this.html(

            $this.html().replace(regex, '</a><span style="background: #fa7373;">$1</span>')

        );

    }

});


忽然笑
浏览 186回答 2
2回答

慕雪6442864

您应该选择 allp和atags inbody而不是 using *which 甚至会选择script标签本身。此外,删除</a>关闭任何锚标记的那个。要不修改锚标记的 HTML,您可以在替换之前检查当前元素是否没有子元素。var regex = /(apples|oranges)/g;$('body a, body p').each(function() {&nbsp; &nbsp; var $this = $(this);&nbsp; &nbsp; var text = $this.text();&nbsp; &nbsp; if (text.match(regex) && $this.children().length===0) {&nbsp; &nbsp; &nbsp; &nbsp; $this.html(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this.html().replace(regex, '<span style="background: #fa7373;">$1</span>')&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><p>I bought some apples.</p><p><a href="oranges.html">I bought some oranges.</a></p><p>I bought some pears.</p>

蓝山帝景

</a>从您的代码中删除。这</a>是关闭任何锚标记。var regex = /(apples|oranges)/g;$('*').each(function() {&nbsp; &nbsp; var $this = $(this);&nbsp; &nbsp; var text = $this.text();&nbsp; &nbsp; if (regex.test(text)) {&nbsp; &nbsp; &nbsp; &nbsp; $this.html(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this.html().replace(regex, '<mark>$1</mark>')&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答