通过jQuery将所有较长的单词从段落转换为链接

时间:2012-11-02 17:18:14

标签: jquery text hyperlink

我对某些实验性想法有疑问。可能只有jQuery Gurus可以帮助我:)

我有一段:

<p>Lorem Ipsum is simply dummy text of the printing 
and typesetting industry. Lorem Ipsum has been the 
industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and
scrambled it to make a type specimen book.</p>

我需要使用jQuery帮助将所有带有至少4个字符的“on-the-fly”onMouseOver转换为从每个单词创建的链接

我不想在HTML中生成它(因为带宽,它会增长到megs),代码看起来像:

<p>
<a href="/search?q=Lorem">Lorem</a> 
<a href="/search?q=Ipsum">Ipsum</a> 
is 
<a href="/search?q=simply">simply</a>
.........
</p>

我也会欣赏onMouseOver的任何文字装饰。

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

$("p").on("hover", function(){
    var content = ​$("p").text();​​​​​
    var words = content.split(" ");
    var length = words.length;
    var newContent = [];

    for(var i = 0; i < length; i++){
        if(words[i].length >= 4){
          newContent.push("<a href='/search?q=simply'>" + words[i] +"</a>")
         }else{
           newContent.push(words[i])
         }
    }     
    $(this).text("");
    $(this).html(newContent.join(" "));              
});  

但是,这不会在您将鼠标悬停后删除a标记,并且会针对每个悬停事件运行。这两个问题都有可能修复,但我会留给你解决这些问题。

<强> EXAMPLE

答案 1 :(得分:0)

将此添加到您的document.ready或document.load call:

$('p').on('hover', 'a', function(){ /* do whatever needs to be done on your link */});
var new_text = [];
$.each($('p').text().split(" "), function(index, word) {
    if (word.length >= 4) {
        word = word.replace(/(\w*)/, '<a href="YOUR URL HERE">\1</a>');
    }
    new_text.push(word);
});
var new_text_as_str = new_text.join(" ");
$('p').html(new_text_as_str);

答案 2 :(得分:0)

不确定这是多么有效,但是:

​$('p').hover(function(){
    var txt = $(this).text();
    txt = txt.replace(/\b([a-z]{4,})\b/ig, '<a class="word" href="/search?q=$1">$1</a>');
    $(this).html(txt);
}, function(){
    $('a.word', this).each(function(){
        $(this).replaceWith($(this).text());
    });
});​

它会在mouseenter上添加链接,并在mouseleave上删除它们。

DEMO:http://jsfiddle.net/8Yqfb/