[英]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.