简体   繁体   English

当div文本等于10时调用警报功能

[英]Call alert function when div text equals 10

I'm working on a game that when you get 10 strikes, there should be a alert telling you Game Over. 我正在开发一款游戏,当您获得10次打击时,应该有个警报告知您游戏结束。 The alert is not working. 警报不起作用。 The StrikeNumber ID is the ID of the DIV that once it is 10, the alert should happen. StrikeNumber ID是DIV的ID,一旦它为10,便会发生警报。 This is pure Java Script. 这是纯Java脚本。

function GameOver(){
if (document.getElementById('StrikeNumber').text === "10"){
    alert("gameOVER");
   }
}


HTML DIVS

<div id="StrikeNumber">
0
</div>
<div id="ScoreNumber">
0
</div>

如果使用的是JQuery,则可以使用.change()方法并在该方法内编写逻辑。

$("#StrikeNumber").change(function(){ alert('strike changed'); });

The div element dose not have a text property. div元素不具有text属性。 You have to use the textContent property. 您必须使用textContent属性。

if (document.getElementById('StrikeNumber').textContent === "10"){
    alert("gameOVER");
   }

get text from doc tag 从doc标签获取文本

There is no text , use innerHTML or textContent . 没有text ,请使用innerHTMLtextContent Your html look like having whitespace so using trim() is a better solution . 您的html看起来有空格,因此使用trim()是更好的解决方案。 You need to learn == & === difference at here 您需要在这里学习=====区别

function GameOver(){
if (document.getElementById('StrikeNumber').innerHTML.trim() == "10"){
     alert("gameOVER");
   }
}

Try following code might help you 尝试使用以下代码可能对您有帮助

 (function() { var x = document.getElementById("StrikeNumber").innerHTML; if (x == 10) { alert("Game Over !!!"); } } )(); 
 <div id="StrikeNumber"> 10 </div> <div id="ScoreNumber"> 0 </div> 

You should use innerHTML to get the content of a div. 您应该使用innerHTML获取div的内容。

function GameOver(){
    if (document.getElementById('StrikeNumber').innerHTML === "10"){
    alert("gameOVER");
   }
}

You also need to make sure that the GameOver() method is called after every div content update. 您还需要确保在每次div内容更新后都调用GameOver()方法。

you can try like this. 您可以尝试这样。

setInterval(function(){
  if(div.textContent === '10') {alert('strike')}
}, 50);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM