我是编码的初学者,并且想知道你们是否可以提供帮助。
我在网上看过很多关于使用innerHTML
,textContent
,value
等来改变标签显示文字的内容,但实际上我无法实现在屏幕上改变。
注意:console.log
会触发并在控制台中显示正确内容的预期文本,但按钮内容在窗口中不会更改。
这是我的html:
<h1 id="myHeading" class="red">JavaScript and the DOM</h1>
<p>Making a web page interactive</p>
<button id="myButton">click me</button>
这是我的Javascript:
const myHeading = document.getElementById('myHeading');
const myButton = document.getElementById('myButton');
let buttonText = myButton.innerText;
console.log(buttonText);
myButton.addEventListener('click', function toggleColor() {
let whatClass = myHeading.classList;
if (whatClass.contains('red')) {
whatClass.remove('red');
whatClass.add('yellow');
buttonText = 'Click me to change text to Red!';
console.log(buttonText);
} else if (whatClass.contains('yellow')) {
whatClass.remove('yellow');
whatClass.add('red');
buttonText = 'Click me to change text to Yellow!';
console.log(buttonText);
}
});
提前致谢,请不要太苛刻!
答案 0 :(得分:1)
您必须实际设置文本。 : - )
myButton.innerHTML = buttonText;
哎呀,我脑子里有jQuery!
答案 1 :(得分:0)
使用myButton.innerText
或myButton.innerHTML
const myHeading = document.getElementById('myHeading');
const myButton = document.getElementById('myButton');
let buttonText = myButton.innerText;
//console.log(buttonText);
myButton.addEventListener('click', function toggleColor() {
let whatClass = myHeading.classList;
if(whatClass.contains('red')) {
whatClass.remove('red');
whatClass.add('yellow');
myButton.innerText = 'Click me to change text to Red!';
}
else if(whatClass.contains('yellow')) {
whatClass.remove('yellow');
whatClass.add('red');
myButton.innerHTML = 'Click me to change text to Yellow!';
}
});
&#13;
.red{background:red}
.yellow{background:yellow}
&#13;
<h1 id="myHeading" class="red">JavaScript and the DOM</h1>
<p>Making a web page interactive</p>
<button id="myButton">click me</button>
&#13;