Bla*_*cal 8 javascript jquery hyperlink keyword
有没有办法让一个单词的每个实例自动变成一个链接?
所以,例如,每当我写"apple"时,它会自动格式化为 <a href="www.apple.com" class="whatever" target="_blank">apple</a>
我假设我可以使用javascript或可能jquery.
谢谢!
非常简单的例子......
jQuery的
var span = $('span');
span.html(function(i,html){
replaceTextWithHTMLLinks(html);
}); // jQuery version 1.4.x
function replaceTextWithHTMLLinks(text) {
var exp = /(apple)/ig;
return text.replace(exp,"<a class='link' href='http://www.$1.com' target='_blank' >$1</a>");
}
Run Code Online (Sandbox Code Playgroud)
HTML
<span>
An apple a day, makes 7 apples a week!
</span>
Run Code Online (Sandbox Code Playgroud)
这是一个简单的jQuery插件,应该可以解决这个问题.它只会选择文本节点,这样如果你有一个带有类apple
或id 的元素,apple
它就不会被替换.另外,如果你有一个链接<a href="#">apple</a>
,它将不会被替换(可能比你需要的多一点,但我想我还是会发布它):
(function($) {
$.fn.replacetext = function(target, replacement) {
// Get all text nodes:
var $textNodes = this
.find("*")
.andSelf()
.contents()
.filter(function() {
return this.nodeType === 3 &&
!$(this).parent("a").length;
});
// Iterate through the text nodes, replacing the content
// with the link:
$textNodes.each(function(index, element) {
var contents = $(element).text();
contents = contents.replace(target, replacement);
$(element).replaceWith(contents);
});
};
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
用法:
$("body").replacetext(/apple/gi, "<a href='http://www.$&.com'>$&</a>");
Run Code Online (Sandbox Code Playgroud)
工作示例:http://jsfiddle.net/andrewwhitaker/VmHjJ/
请注意,由于使用了$("*")
选择器,这可能会变得非常低效.如果可能,您应该用更具体的东西替换它(或者.find("*").andSelf()
完全删除该部分并将插件传递给更具体的选择器).
归档时间: |
|
查看次数: |
2775 次 |
最近记录: |