我已经创建了这个函数,它从字符串中的单词数量中获取值,并将其与自定义价格相乘。这两个值都取自输入字段。但是,通过调用此函数" NaN"会给我一个错误。你能在这里发现问题吗?
<!DOCTYPE html>
<html>
<head>
<title>Telegramma</title>
<script>
var string = document.getElementById("text");
var words = new Number (string.split(" ").length);
var price = new Number (document.getElementById("price").value);
function showPrice(){
var total = new Number (words * price);
document.getElementById("showPrice").innerHTML = total;
}
</script>
</head>
</body>
</html>
&#13;
<body>
Text:<input id = "text" type = "text"/>
Price per a word €<input id = "price" min="0.01" step="0.01" type = "number" />
<button onclick = "showPrice()">Get the full price</button>
<p id = "showPrice"> </p>
&#13;
答案 0 :(得分:1)
您必须在showPrice()函数中分配string
,words
和price
变量。您的代码永远不会分配这些值。
此外,这一行
var string = document.getElementById("text");
指定输入元素而不是内容。你需要使用
var string = document.getElementById("text").value;
获得理想的结果。
以下是完整的代码示例:
function showPrice(){
var text = document.getElementById("text").value;
var words = new Number (text.split(" ").length);
var price = new Number (document.getElementById("price").value);
var total = new Number (words * price);
document.getElementById("showPrice").innerHTML = total;
}
答案 1 :(得分:0)
这是因为当您的脚本正在执行时,尚未创建内容。将所有脚本放在body
关闭标记之前的所有内容之后。或者在身体负荷事件上执行一切。