jquery: find a string and wrap it in an tag?

后端 未结 2 524
梦毁少年i
梦毁少年i 2020-12-09 21:49

i\'ve got this:

相关标签:
2条回答
  • 2020-12-09 22:18

    Use :contains filter selector:

    $('p.hidden:contains("click here")')
    

    To wrap it in link:

    $('p.hidden:contains("click here")').html()
    .replace('click here', '<a href="url">click here</a>');
    

    To wrap whole text in link:

    $('p.hidden:contains("click here")')
    .html('<a href="url">' + $('p.hidden:contains("click here")').text() + '<a>');
    

    More Info:

    • http://api.jquery.com/contains-selector/
    0 讨论(0)
  • 2020-12-09 22:34

    Don't use HTML string hacking. Imagine what would happen if you tried to replace over <span title="blah click here blah">...</span> with an <a> tag... massively broken markup. And that's only the beginning of the problems.

    Instead, iterate over the text nodes in the part of the document you want to examine, looking for text matches and inserting a new link using DOM-style methods.

    jQuery doesn't really help you much here as it has no functionality for handling text nodes. Instead, use something like the findText() function from this question and use splitText to split up the text node:

    findText($('#fancy_hover')[0], /\bClick here\b/gi, function(node, match) {
        node.splitText(match.index+match[0].length);
        var link= document.createElement('a');
        link.href= 'http://www.example.com/';
        link.appendChild(node.splitText(match.index));
        node.parentNode.insertBefore(link, node.nextSibling);
    });
    
    0 讨论(0)
提交回复
热议问题