我正在尝试将特定的单词或短语转换为与jQuery的链接。到目前为止,我只是在悬停事件后成功地将带有class =“link”的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>");
});
答案 0 :(得分:2)
不使用悬停事件来启动更改,而是使用每个匹配元素在您调用它时执行的每个方法。
所以
$('span.link').each(function () {
$(this).replaceWith("<a href='http://mydomain.com'>" + $(this).text() + "</a>");
});
将您的所有跨度转换为一次性链接..