2011-05-27 44 views
0

爲什麼此代碼不能正確工作?如果某人選擇了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> 
+1

你對這個調用有什麼期望:'a = document.getElementById();'? – 2011-05-27 02:18:29

回答

0

我想你會看到這個問題,如果你添加一個 警報(一);在if(...)之前有 - 我的猜測是你沒有得到你期望的值。

0

document.getElementById()方法需要查找ID的參數。例如:

document.getElementById("1599") 

並且將返回具有該ID的文檔元素。不知道當沒有參數傳遞時會返回什麼。

+1

'不知道當沒有參數傳遞時它會返回什麼。 [specs](http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-getElBId)可能會有幫助。不提供參數是一個錯誤,所以返回值依賴於瀏覽器 - Firefox拋出錯誤,IE返回'null'。 :-) – RobG 2011-05-27 02:31:28

1

您需要讓showPrice知道您想要顯示警報的元素。現在,你實際上並沒有選擇任何與document.getElementByIda將在此時爲nullundefined)。

有一堆不同的方式去這樣做,但要保持它接近你的當前實現,我可能會做這樣的事情:

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; 
} 

Fiddle here