gpt4 book ai didi

javascript - 元素值比较的结果不正确

转载 作者:太空宇宙 更新时间:2023-11-04 14:30:51 24 4
gpt4 key购买 nike

我正在制作一个 html 纸牌游戏,它有一个带有大于或等于比较运算符的 if 语句。但当资金低于价格时,它仍然运行,就好像你有需要的钱一样。

HTML

    <article id="moneysys">
<p id="ptdabtd" >Click 'Set Cash' To Enter A Starting Ammount. (Button Will Be Deleted Once Finished)</p>
<button id="scda" onclick="setcash();">Set Cash.</button>
<br />
<div class="cash">Cash: <span id="cash">0</span></div>
<div>Pack Price: <span id="packprice">50</span></div>
</article>
<main>
<center>
<button class="open" onclick="opencards()">Open Cards.</button>
<br />
<img class="card" src="images/blank.png" id="canvas" />
<img class="card" src="images/blank.png" id="canvas1" />
<img class="card" src="images/blank.png" id="canvas2" />
<img class="card" src="images/blank.png" id="canvas3" />
<img class="card" src="images/blank.png" id="canvas4" />
</center>
</main>

JavaScript

function setcash(){
var wcash = prompt("Please Enter How Much Cash You Want To Start With", "Cash Wanted");
document.getElementById("cash").innerHTML = wcash;
document.getElementById("scda").remove();
document.getElementById("ptdabtd").remove();

}

var cards = new Array("images/1.png", "images/2.png", "images/3.png", "images/4.png", "images/5.png","images/6.png", "images/7.png", "images/8.png", "images/9.png");

var pack = document.getElementById("packprice");
var ccash = document.getElementById("cash");

var pc = Number(pack);
var cash = Number(ccash);

function opencards(){
if (cash >= pc){
var randomNum = Math.floor(Math.random() * cards.length);
document.getElementById("canvas").src = cards[randomNum];
document.getElementById("canvas1").src = cards[randomNum];
document.getElementById("canvas2").src = cards[randomNum];
document.getElementById("canvas3").src = cards[randomNum];
document.getElementById("canvas4").src = cards[randomNum];
cash = cash - pc;
} else{
alert("not")
}
};

最佳答案

您只能获取元素本身,而不是元素的实际值。然后你试图从一个元素中获取一个数字。由于实际元素不会改变(无论 innerhtml 设置的是什么),您在比较中每次都会得到相同的结果。

var pack = document.getElementById("packprice"); //this gets you the element
var ccash = document.getElementById("cash"); //this gets you the element

改为尝试:

var pack = document.getElementById("packprice").innerHTML;
var ccash = document.getElementById("cash").innerHTML;

你也可以省略

var pc = Number(pack);
var cash = Number(ccash);

关于javascript - 元素值比较的结果不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36976820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com