-3

我对一些实验性的想法有疑问。可能只有 jQuery 大师可以在这里帮助我 :)

我有一段:

<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 中生成它(因为带宽,它会增长到兆),该代码将如下所示:

<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。

4

3 回答 3

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在您悬停后删除标签,并将针对每个悬停事件运行。这两个问题都有可能修复,但我会把这些留给你去解决。

例子

于 2012-11-02T17:28:28.713 回答
0

将此添加到您的 document.ready 或 document.load 调用中:

$('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);
于 2012-11-02T17:28:31.237 回答
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

演示:http: //jsfiddle.net/8Yqfb/

于 2012-11-02T17:29:50.513 回答