[英]alerts in else statements
为什么这段代码不能正常工作? 如果有人选择了 id 为“1599”的东西,那么警报将显示“$1,599.00”。 如果 id 不匹配,则警报应显示“$1,499.00”。 但事实并非如此。 有人可以帮我解决这个问题吗?
谢谢
<html>
<script type="text/javascript">
function showPrice(){
var a = document.getElementById();
if (a == "1599"){
alert("$1,599.00");
}
else {
alert("$1,499.00");
}
}
<body>
<div class="hc_right">
<input type="button" class="spc" value="Price" onclick="showPrice()" />
<p class="price" id="1599">$1,599.00</p>
</div>
<div class="hc_right">
<input type="button" class="spc" value="Price" onclick="showPrice()" />
<p class="price" id="1499">$1,499.00</p>
</div>
</div>
</body>
</html>
您需要让showPrice
知道要显示警报的元素。 现在,您实际上并没有使用document.getElementById
选择任何内容(此时a
将是null
或undefined
)。
go 有很多不同的方法来执行此操作,但为了使其接近您当前的实现,我可能会执行以下操作:
HTML
<div class="hc_right">
<input type="button" class="spc" value="Price" onclick="showPrice(1599)" />
<p class="price" id="1599">$1,599.00</p>
</div>
<div class="hc_right">
<input type="button" class="spc" value="Price" onclick="showPrice(1499)" />
<p class="price" id="1499">$1,499.00</p>
</div>
</div>
Javascript
function showPrice(a){
if (a == "1599"){
alert("$1,599.00");
}
else {
alert("$1,499.00");
}
return false;
}
我认为如果您添加警报(a),您会看到问题; 在 if(...) 之前 - 我的猜测是你没有得到你期望的价值。
document.getElementById()
方法采用要查找的 ID 参数。 就像是:
document.getElementById("1599")
并将返回具有该 ID 的文档元素。 不知道当没有参数传递时它会返回什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.