首页 > 解决方案 > 将课程内容更改为 href

问题描述

<div class="container">
    <span class="text1">test</span>
    <span class="text2">test</span>
</div>

我想在我的函数内的javascript中将“text2”更改为href,如下所示:

var x=document.getElementsByClassName("text2");  // Find the elements
x.innerHTML="<a href='https://test.com'>test</a>";    // Change the content

所以“text2”的内容变成了一个名为“test”的超链接,它指的是“https://test.com”

标签: javascripthtml

解决方案


你可以这样做:

var element = document.querySelector(".text2"); // Find the first element with the class text2
element.innerHTML = "<a href=\"https://test.com\">test</a>"; // Change the content including all HTML elements that might be in there to the value specified escaping the " character
<div class="container">
    <span class="text1">test</span>
    <span class="text2">test</span>
</div>

问题是您没有逃脱 " 字符,您也可以做到这一点,而无需像这样转义:

var element = document.querySelector(".text2"); // Find the first element with the class text2
element.innerHTML = "<a href='https://test.com'>test</a>"; // Change the content including all HTML elements that might be in there to the value specified
<div class="container">
    <span class="text1">test</span>
    <span class="text2">test</span>
</div>


推荐阅读