簡體   English   中英

使用串聯的innerHTML中的href

[英]A href in innerHTML using concatenation

我查看了通過innerHTML放入href的另一個答案,但在我的特定示例中無法使其正常工作。

我正在嘗試添加鏈接的單詞“任務”,但始終收到錯誤“意外的標識符”。

function myFunction(){
    //Select Paid Membership Text under Level
    var str = document.getElementById("pmpro_levels_table").innerHTML;
    var res = str.replace("Paid Membership", "$1 monthly to fund our ");
    //replace text
    document.getElementById("pmpro_levels_table").innerHTML = res + "<a href='"simpledmedicines.com/mission/"'>mission</a>";
}
myFunction();

我認為我做錯的部分是:

document.getElementById("pmpro_levels_table").innerHTML = res + "<a href='"simpledmedicines.com/mission/"'>mission</a>";

特別:

.innerHTML = res + "<a href='"simpledmedicines.com/mission/"'>mission</a>";

如果您有興趣,我可以為您提供略有不同的解決方案。

 function myFunction(){ //Select Paid Membership Text under Level var str = document.getElementById("pmpro_levels_table").innerHTML; var res = str.replace("Paid Membership", "$1 monthly to fund our "); //replace text const table = document.getElementById("pmpro_levels_table"); table.innerHTML = res; // create anchor element const anchor = document.createElement('a'); // set anchor href attribute anchor.setAttribute('href', 'simpledmedicines.com/mission/'); // set anchor text anchor.textContent = 'mission'; // append anchor to your table table.appendChild(anchor); } myFunction(); 

您只需要從定位標記中刪除雙引號即可。 請參閱此JSFiddle和下面的更新代碼:

<div id="pmpro_levels_table">
  Paid Membership
</div>

function myFunction(){
    //Select Paid Membership Text under Level
    var str = document.getElementById("pmpro_levels_table").innerHTML;
    var res = str.replace("Paid Membership", "$1 monthly to fund our ");
    //replace text
    document.getElementById("pmpro_levels_table").innerHTML = res + "<a href='simpledmedicines.com/mission/'>mission</a>";
}
myFunction();

暫無
暫無

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

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