我开始学习 JS,所以我有一些非常基本的问题......
在这种情况下,我正在尝试做一个“网球积分”计数器。所以,我做到了,当一些玩家得到 45 分时,应用程序会显示“玩家 1 赢了这盘”
问题是……我想接受“玩家 1 赢了这盘”,当它出现时,我想显示一个警告,说“你想玩另一盘吗?”但是我做不到...
我有这个空白
en HTML。我写了 JS 代码,所以当玩家达到 45 分时,
变成“玩家 1 赢了这盘”
<p id="winner1"></p>
然后,我尝试“获取”那个新字符串并创建一个警报
let winner1 = document.getElementById("winner1")
if(winner1 == "player 1 won the set"){
alert("do you want to play another set?")
}
但它不起作用。我尝试使用 winner1.value,但它也不起作用。 似乎我需要一些始终“监听”
值的东西,但我不知道该怎么做......
抱歉这么基本的问题。
提前致谢!
if(winner1.innerText == "player 1 won the set"){
alert("do you want to play another set?")
}
将状态存储在变量中,而不是在 DOM 中。对于维护您的代码的程序员来说,这将更简单、更常规、更清晰,并且更不容易出现错误(例如,当您更改屏幕消息的措辞时)。
要监视 HTML 元素的变化并在它发生变化时运行 JavaScript 方法,您可以使用 MutationObserver API。 MutationObserver API 允许您观察 DOM 树的变化并在发生特定变化时接收通知。
<p id="winner1"></p>
<script>
// Get the element we want to watch
const watchedElement = document.querySelector('#winner1');
// Create a new MutationObserver and specify a callback function
const observer = new MutationObserver((mutationsList) => {
// Run our method when the element changes
myMethod();
});
// Start observing the element for changes
observer.observe(watchedElement, { attributes: true, childList: true,
subtree: true });
// Define the method we want to run when the element changes
function myMethod() {
if(winner1 == "player 1 won the set"){
alert("do you want to play another set?")
}
}
</script>
在这个例子中,我们正在观察#winner1 p 标签的变化。当发生任何变化时,将调用 myMethod() 函数,并显示警报。
您可以通过调整传递给 observer.observe() 的选项参数来自定义观察者以监视元素的特定类型的变化。例如,您可以通过设置 { attributes: true } 仅监视元素属性的变化,或者通过设置 { childList: true } 监视其子元素的变化。
希望有用