我在<p>标记内有一些纯文本,试图自动查找所有链接和所有标签。我将脚本分为两个部分:


首先应用主题标签包装器
然后应用链接包装
执行功能将同时运行以上两个功能


我想使用纯JavaScript。获取和替换HTML的JS Equiv是什么?

的HTML

<p>
Thank you to @InstagramUsername for the award. I’m glad to contribute to the success of the property sector through the efforts of @AnotherUser.
#HashtagAwards #Another
</p>


JS

function getHashTags(){
 // Find # and wrap in <a>
    let hashTxt = document.querySelector("p")[0].html();
    hashTxt = hashTxt.replace(/#(\w+)/g, "<a href='https://instagram.com/explore/tags?q=$1'>$1</a>");
    hashTxt.html(hashTxt);
}

function getLinks(){
 // Find @ and wrap in <a>
    let linkStr = document.querySelector("p")[0].html();
    linkStr = linkStr.replace(/@(\w+)/g, "<a href='https://instagram.com/$1/'>@$1</a>");
    linkStr.html(linkStr);
}

function execute(){
    getHashTags()
    getLinks()
}

execute()

最佳答案

几乎可以工作,您未正确设置innerHTML,因为hashTxt不是元素。

function getHashTags(){
 // Find # and wrap in <a>
    let hashTxt = document.querySelector("p").innerHTML;
    hashTxt = hashTxt.replace(/#(\w+)/g, "<a href='https://instagram.com/explore/tags?q=$1'>$1</a>");
    document.querySelector("p").innerHTML = hashTxt;
}

function getLinks(){
 // Find @ and wrap in <a>
    let hashTxt = document.querySelector("p").innerHTML;
    hashTxt = hashTxt.replace(/@(\w+)/g, "<a href='https://instagram.com/$1/'>@$1</a>");
    document.querySelector("p").innerHTML = hashTxt;
}


演示版



function getHashTags(){
 // Find # and wrap in <a>
    let hashTxt = document.querySelector("p").innerHTML;
    hashTxt = hashTxt.replace(/#(\w+)/g, "<a href='https://instagram.com/explore/tags?q=$1'>$1</a>");
    document.querySelector("p").innerHTML = hashTxt;
}

function getLinks(){
 // Find @ and wrap in <a>
    let hashTxt = document.querySelector("p").innerHTML;
    hashTxt = hashTxt.replace(/@(\w+)/g, "<a href='https://instagram.com/$1/'>@$1</a>");
    document.querySelector("p").innerHTML = hashTxt;
}

function execute(){
    getHashTags()
    getLinks()
}

execute()

<p>
Thank you to @InstagramUsername for the award. I’m glad to contribute to the success of the property sector through the efforts of @AnotherUser.
#HashtagAwards #Another
</p>

关于javascript - document.querySelector不是函数-尝试用社交包装器替换#和链接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49853758/

10-14 14:44
查看更多