[英]content replace js script fails
The code below does not appear to function properly. 下面的代码似乎无法正常运行。 newH2Text should replace para1.
newH2Text应该替换para1。 This does not happen.
这不会发生。 I used Sublime, then looked through the browser console, and even on SO's code snippet.
我使用了Sublime,然后浏览了浏览器控制台,甚至浏览了SO的代码段。 I am almost certain I have the code verbatim.
我几乎可以肯定我有逐字记录的代码。
The first paragraph, which has its own id attribute should be replaced by newH2Text which is created in my JS script. 具有自己的id属性的第一段应替换为在我的JS脚本中创建的newH2Text。 I can't find my mistake here.
我在这里找不到我的错误。 Please help.
请帮忙。
PS the refresh button works properly. PS刷新按钮正常工作。 No issue there.
那里没有问题。
function replaceHeading(){ var newH2=document.createElement("h2"); var newH2Text=document.createTextNode("Welcome"); newH2.appendChild(newH2Text); var myDiv=document.getElementById("id1"); var oldP=document.getElementById("para1"); myDiv.replaceChild(NewH2,oldP); } window.onload=function() { document.getElementById("btn").onclick=replaceHeading; }
<div id="id1"> <p id="para1">Welcome to my web page.</p> <p id="para2">Take a look around.</p> <input type="button" id="btn" value="Replace Element"> <br> <input type="button" value="refresh" onclick="location.reload()"> </div>
NewH2
is capitalized but should be newH2
with a lowercase. NewH2
为大写字母,但应为小写的newH2
。
myDiv.replaceChild(newH2,oldP);
See this fiddle for an example 看到这个小提琴的例子
Update 更新
To catch these errors earlier you can use " strict mode ". 为了更早地发现这些错误,您可以使用“ 严格模式 ”。 An example of this would be:
例如:
;(function(){
"use strict";
function replaceHeading(){
var newH2=document.createElement("h2");
var newH2Text=document.createTextNode("Welcome");
newH2.appendChild(newH2Text);
var myDiv=document.getElementById("id1");
var oldP=document.getElementById("para1");
myDiv.replaceChild(NewH2,oldP);
}
}());
Which would give you the error Uncaught ReferenceError: NewH2 is not defined
. 这将给您带来错误
Uncaught ReferenceError: NewH2 is not defined
。
There are at least two different ways todo what you are trying: 至少有两种不同的方法可以执行您要尝试的操作:
function replaceHeading(){ /***** CORRECTED AND WORKING var newH2=document.createElement("h2"); var newH2Text=document.createTextNode("Welcome"); newH2.appendChild(newH2Text); var oldP=document.getElementById("para1"); document.getElementById("id1").replaceChild(newH2,oldP); *//// // OR a more simpler way document.getElementById("para1").innerHTML = "<h2>Welcome</h2>"; } window.onload=function() { document.getElementById("btn").onclick=replaceHeading; }
<div id="id1"> <p id="para1">Welcome to my web page.</p> <p id="para2">Take a look around.</p> <input type="button" id="btn" value="Replace Element"> <br> <input type="button" value="refresh" onclick="location.reload()"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.