簡體   English   中英

如何從捕獲的innerHTML值構造JavaScript中的鏈接?

[英]How to construct a link in JavaScript from captured innerHTML value?

假設我有

    <a href="#" id="someid">findme</a>  (innertext can be whatever other than findme)

當我點擊“findme”時,我想重定向到“/?q=findme”頁面。 (該值應該在 /?q= 之后插入以創建一個新鏈接,頁面應該重定向到該鏈接。)如何使用 javascript 做到這一點?

獲取鏈接的內部文本並修改 href 屬性以指向您的首選位置。

 const linkElement = document.getElementById('someid'); //get your link element by id const innerValue = linkElement.innerText // get inner text value linkElement.href = '/?q=' + innerValue // set href attribute
 <a href="#" id="someid">findme</a>

像這樣

 const lnk = document.getElementById("someid"); // direct access lnk.href = "/?q="+lnk.textContent; // set the href attribute
 <a href="#" id="someid">findme</a>

更多信息:

 [...document.querySelectorAll("#container a")] // get the html node list of anchors in the container .forEach(lnk => lnk.href = "/?q="+lnk.textContent); // set each of the hrefs
 <div id="container"> <a href="#" id="find">findme</a> <a href="#" id="goto">goto</a> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM