gpt4 book ai didi

javascript - 在 jQuery 中添加指向特定短语或关键字的链接

转载 作者:行者123 更新时间:2023-11-29 22:41:34 24 4
gpt4 key购买 nike

我正在尝试将特定的单词或短语转换为 jQuery 链接。到目前为止,我只成功地在悬停事件后将带有 class="link"的跨度更改为 anchor 标记。我的问题是我希望它们在页面加载时更改。作为一个额外的好处,最好定位任何单词或短语而不必将它们放在 span 中。

$('span.link').hover(function () {

$(this).replaceWith("<a href='http://mydomain.com'>" + $(this).text() + "</a>");

});

只有当他们悬停在文本上时才有效,但我真正想要的是这样的:

var keyword = 'my keyword';

var link = $(document).find(keyword);

$(document).ready(function() {
link.replaceWith("<a href='http://mydomain.com'>" + $(this).text() + "</a>");
});

最佳答案

不是使用悬停事件来启动更改,而是使用 each 方法,该方法将在您调用它时为每个匹配的元素执行..

所以

$('span.link').each(function () {

$(this).replaceWith("<a href='http://mydomain.com'>" + $(this).text() + "</a>");

});

将一次性将所有跨度转换为链接..

关于javascript - 在 jQuery 中添加指向特定短语或关键字的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2394801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com