使用JavaScript自动为网址文本添加超链接

Kevin 杂记 694 次浏览 18条评论

有些情况可能需要用到这个,例如网页里有大量链接,以文本形式存在。手动添加超链接显然不现实,这时可以用JavaScript配合正则匹配和replace()替换函数解决。将下面代码加至</body>前,绑定内容父标签ID名称即可使用,原生JS用法,不用加载jQuery库。

HTML

<div id="demo">包含网址的文本内容</div>

JavaScript

window.onload = function() {
    var label = document.getElementById("demo");
    var text = label.innerHTML;
    var regular = /((https|http):\/\/[\w.\/\:\-]+)(?![^<]+>)/gi;
    label.innerHTML = text.replace(regular, "<a href='$1' target='_blank'>$1</a>");
}

评论列表

  1. #1

    Hi, very nice website, cheers!
    ——————————————————
    Need cheap and reliable hosting? Our shared plans start at $10 for an year and VPS plans for $6/Mo.
    ——————————————————
    Check here: https://www.reliable-webhosting.com/

  2. #2

    priligy dapoxetine for sale https://salemeds24.wixsite.com/dapoxetine

  3. #3

    where can i order cialis online http://www.lm360.us/

  4. #4

    super vidalista 20mg https://vidalista.mlsmalta.com/

  5. #5

    ivermectin usa https://ivermectin.webbfenix.com/

  6. #6

    sildenafil citrate 20 mg cost http://droga5.net/

  7. #7

    vidalista when to take https://vidalista.buszcentrum.com/

  8. #8

    has hydroxychloroquine been successful https://hydroxychloroquine.mlsmalta.com/

  9. #9

    how much ivermectin is too much https://ivermectin.mlsmalta.com/

  10. #10

    generic viagra and vidalista https://vidalista40mg.mlsmalta.com/

  11. #11

    warnings for cialis https://wisig.org/

  12. #12

    is tamoxifen used after menopause https://tamoxifen.mrdgeography.com/

  13. #13

    need refill no doctor https://buymeds.mlsmalta.com/

  14. #14

    proair hfa inhaler https://amstyles.com/

  15. #15

    hydroxychloroquine treating covid 19 https://hydroxychloroquinee.com/

  16. #16

    how much is cialis 10mg https://cleckleyfloors.com/

  17. #17

    how to stop taking plaquenil https://hydroxychloroquine.wisig.org/

  18. #18

    cenforce patent expiration date extended http://cavalrymenforromney.com/

发表评论

电邮地址用于 Gravatar 头像显示,不会被公开可见。