2017-04-09 31 views
-1

我已經使這個函數從字符串中存在的單詞數中獲取價值,並將其從自定義價格中乘以它。這兩個值都來自輸入字段。然而,它通過調用這個函數「NaN」來給我一個錯誤。你能在這裏發現問題嗎?無法讀取空值返回的屬性'分割'NaN

<!DOCTYPE html> 
 
<html> 
 
\t <head> 
 
\t \t <title>Telegramma</title> 
 

 
\t \t <script> 
 
\t \t var string = document.getElementById("text"); 
 
\t \t var words = new Number (string.split(" ").length); 
 
\t \t var price = new Number (document.getElementById("price").value); 
 

 
\t \t function showPrice(){ 
 
\t \t var total = new Number (words * price); 
 
\t \t \t document.getElementById("showPrice").innerHTML = total; 
 
} 
 
\t \t </script> 
 

 
\t </head> 
 

 

 
\t </body> 
 

 
</html>
<body> 
 
Text:<input id = "text" type = "text"/> 
 
Price per a word &euro;<input id = "price" min="0.01" step="0.01" type = "number" /> 
 

 
<button onclick = "showPrice()">Get the full price</button> 
 

 
<p id = "showPrice"> </p>

+0

把'script'標籤body'標籤後'。 – gurvinder372

+1

腳本出現的地方不如代碼正確。 'string','words'和'price'的聲明和初始化應該在**函數內部,而不是在外部。隨着這一變化,'

0

那是因爲當你的腳本執行,在不創建的內容,但。將所有內容放在body關閉標記之前的所有內容之後。或者在身體負載事件上執行所有事情