使用连接的innerHTML中的href

时间:2018-04-22 17:30:20

标签: javascript

我查看了另一个通过innerHTML设置href的答案,但是在我的特定示例中无法使其工作。

我试图添加链接词" mission"但不断收到错误"意外的标识符"。

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>";

2 个答案:

答案 0 :(得分:0)

如果您有兴趣,我可以为您提供略有不同的解决方案。

&#13;
&#13;
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();
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您只需要从锚标记中删除双引号即可。请参阅此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();