其他语句中的警报
为什么此代码不能正确工作?如果某人选择了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>
我想你会看到这个问题,如果你添加一个 警报(一);在if(...)之前有 - 我的猜测是你没有得到你期望的值。
document.getElementById()
方法需要查找ID的参数。例如:
document.getElementById("1599")
并且将返回具有该ID的文档元素。不知道当没有参数传递时会返回什么。
'不知道当没有参数传递时它会返回什么。 [specs](http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-getElBId)可能会有帮助。不提供参数是一个错误,所以返回值依赖于浏览器 - Firefox抛出错误,IE返回'null'。 :-) – RobG 2011-05-27 02:31:28
您需要让showPrice
知道您想要显示警报的元素。现在,你实际上并没有选择任何与document.getElementById
(a
将在此时为null
或undefined
)。
有一堆不同的方式去这样做,但要保持它接近你的当前实现,我可能会做这样的事情:
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 = document.getElementById();'? – 2011-05-27 02:18:29