我正在尝试编写一个javascript函数,这样当一个按钮被点击时,所有的HTML段落元素"p“将被高亮显示为黄色,然后HTML按钮文本将变为"Click to unhighlight”(下面的代码在else语句完全起作用之前,所有段落都被高亮显示,按钮文本也会改变)。我尝试使用"location.reload();“重新加载页面,但似乎不起作用。
window.onload = function() {
var button = document.getElementsByTagName("button");
button[0].onclick = changeBackground;
}
function changeBackground() {
var myParas = document.getElementsByTagName("p");
for (var i = 0; i < myParas.length; i++) {
myParas[i].style.backgroundColor = "yellow";
}
var firstClick = true;
var b = document.getElementById("button");
if (firstClick) {
b.innerHTML = "Click to unhighlight";
firstClick = false;
} else {
location.reload();
firstClick = true;
}
}
任何关于如何正确调用"location.reload();“函数的建议都将不胜感激。提前谢谢。
发布于 2018-10-30 05:57:38
问题是else语句永远不会被调用,因为每次调用changeBackGround方法并将变量设置为true时,"firstClick“变量总是为true。
为了避免这种情况,只需在方法外声明变量即可,例如:
var firstClick=true;
function changeBackground(){
var myParas = document.getElementsByTagName("p");
for (var i = 0; i < myParas.length; i++) {
myParas[i].style.backgroundColor = "yellow";
}
var b = document.getElementById("button");
if (firstClick){
b.innerHTML = "Click to unhighlight";
firstClick = false;
}else{
location.reload();
firstClick = true;
}
}
发布于 2018-10-30 06:02:35
另一种方法是使用switch case。
<button id="changeButton">Make my paragraphs Yellow</button>
<script>
var theToggle = document.getElementById("changeButton");
var toggleMe = document.getElementsByTagName("p");
toggleMe.toggleStatus = "on";
theToggle.onclick = function(){
switch(toggleMe.toggleStatus){
case "on":
toggleMe.toggleStatus="off";
for (var i = 0; i < toggleMe.length; i++) { toggleMe[i].style.backgroundColor = 'yellow'; }
theToggle.textContent = "Make my paragraphs White";
break;
case "off":
toggleMe.toggleStatus="on";
for (var i = 0; i < toggleMe.length; i++) { toggleMe[i].style.backgroundColor = 'white'; }
theToggle.textContent = "Make my paragraphs Yellow";
break;
}
}
</script>
希望能解决这个问题。
https://stackoverflow.com/questions/53054258
复制相似问题