我尝试更换">>"用"你好"。它不会起作用。为什么?任何暗示都是指定的。感谢。
<p id="demo">a string with >> in it.</p>
<button onclick="myFunction()">Replace ">>" with "hello"</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(">>", "hello");
document.getElementById("demo").innerHTML = res;
}
</script>
答案 0 :(得分:2)
您正在获取HTML实体,请改用.textContent
。
.innerHTML
返回浏览器解析的字符串,因此,例如,此字母á
将转换为á
。因此,您使用>>
获得innerHTML
。
<p id="demo">a string with >> in it.</p>
<button onclick="myFunction()">Replace ">>" with "hello"</button>
<script>
function myFunction() {
console.log(document.getElementById("demo").innerHTML); // just to illustrate!
var str = document.getElementById("demo").textContent;
var res = str.replace(">>", "hello");
document.getElementById("demo").textContent = res;
}
</script>
&#13;
addEventListener
将事件绑定到元素。document.getElementById("demo")
存储到变量中,以避免在当前DOM中重复搜索。*
document.querySelector('button').addEventListener('click', myFunction);
function myFunction() {
var demoElement = document.getElementById("demo");
console.log(demoElement.innerHTML); // just to illustrate!
var str = demoElement.textContent;
var res = str.replace(">>", "hello");
demoElement.textContent = res;
}
&#13;
<p id="demo">a string with >> in it.</p>
<button>Replace ">>" with "hello"</button>
&#13;
Element.innerHTML
Element属性
innerHTML
属性用于获取或设置表示序列化HTML的字符串,该字符串描述元素的后代。
Node.textContent
Node.textContent
属性表示节点及其后代的文本内容。
EventTarget.addEventListener()
答案 1 :(得分:2)
问题是您正在设置 .innerHTML
,它将字符串解析为HTML。当然,>
在HTML中具有特殊含义。
相反,请使用 .textContent
,它将字符串视为原始文本而不对其进行解析。
function myFunction() {
var str = document.getElementById("demo").textContent;
var res = str.replace(">>", "hello");
document.getElementById("demo").textContent = res;
}
<p id="demo">a string with >> in it.</p>
<button onclick="myFunction()">Replace ">>" with "hello"</button>
当HTML解析器将字符串视为HTML并在字符串中查找有效的HTML时,它会正确地将其解析为HTML,但如果它找到了无效的迷路<
和>
HTML,它将它们转移到<
和>
的 HTML entities ,您可以在此处看到:
// With .innerHTML:
// Valid HTML in the string returns the string and the HTML
console.log(document.querySelector("div").innerHTML);
// HTML syntax, but not valid HTML, returns HTML entities
console.log(document.querySelector("p").innerHTML);
// With .textContent:
// Valid HTML is not returned - only the text
console.log(document.querySelector("div").textContent);
// HTML Syntax, but not valid HTML, returns unaltered string
console.log(document.querySelector("p").textContent);
h1 { font-size:1.1em; }
<h1>Both of the following will have .innerHTML used on them: </h1>
<div>A string with <span>valid HTML</span> in it.</div>
<p>A string with >>> HTML syntax <<<, but not valid HTML in it.</p>
答案 2 :(得分:1)