javascript - 将课程内容更改为 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”
解决方案
你可以这样做:
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>
推荐阅读
- php - 从 MySQL/PHP 修复 JSON 格式
- javascript - 详细的堆栈跟踪:错误:找不到模块“条带”
- javascript - React Antd 动态下拉菜单
- sql - 比较查询中的两个字段
- c++ - 在 Darwin 上交叉编译 C++ 到 ARM
- web-scraping - Webscraping - 数据提取 - web scraper google chrome 扩展
- python - 当使用 .get 方法调用 IntVar() 值时,使用循环在 Tkinter 中创建检查按钮会导致意外行为
- python - 递归洪水使用python和numpy填充图像
- java - 验证字符串是用 Java 编码的 UTF-8
- mysql - Perc perc per football cluf 总分