这是javascript代码
<script type="text/javascript">
function Choose() {
var n1, Price, Stock;
n1 = document.getElementById("product").value;
if (n1 == "1")
Price = 12.5;
Stock = 15;
else
Price = "40";
Stock = "5";
document.getElementById("price") = Price;
document.getElementById("stock") = Stock;
}
< /script
HTML正文
<select id="product"><option value="1" >PRODUCT 1</option>
PRODUCT 2
<input type="text" value="0" id="price">
<input type="text" value="0" id="stock">
我需要帮助!为什么这段代码不起作用? 我的失败在哪里?
答案 0 :(得分:3)
您需要设置DOM元素的值
document.getElementById("price").value = Price;
document.getElementById("stock").value = Stock;
您需要将DOM元素的属性value
而不是DOM元素本身设置为整数值
此外,您在if-else块周围缺少{}
。我假设您错过了>
运算符,而关闭脚本标记是一个拼写错误而不是原始代码。如果它在原始代码中也改变它
<script type="text/javascript">
function Choose() {
var n1, Price, Stock;
n1 = document.getElementById("product").value;
if (n1 == "1") {
Price = 12.5;
Stock = 15;
}
else {
Price = "40";
Stock = "5";
}
document.getElementById("price").value = Price;
document.getElementById("stock").value = Stock;
}
< /script>
function Choose() {
var n1, Price, Stock;
n1 = document.getElementById("product").value;
if (n1 == "1") {
Price = "12.5";
Stock = "15";
} else {
Price = "40";
Stock = "5";
}
document.getElementById("price").value = Price;
document.getElementById("stock").value = Stock;
}
&#13;
<select id="product">
<option value="1" >Product1</option>
<option value="2">Product2</option>
</select>
<input type="button" value="Submit" onClick="Choose()">
<input type="text" id="price"/>
<input type="text" id="stock"/>
&#13;
答案 1 :(得分:2)
<script type="text/javascript">
function Choose(){
var n1,Price,Stock ;
n1 = document.getElementById("product").value;
if (n1 == "1") {
Price = 12.5;
Stock = 15;
}
else {
// place it in block
Price = "40";
Stock = "5";
} // place it in block
document.getElementById("price").value = Price;
document.getElementById("stock").value = Stock;
}
</script>
假设你得到的错误是错误的。 如果在条件或循环下写入多个语句,则必须将其作为块
答案 2 :(得分:1)
首先,情况可能并非如此,但您缺少脚本的结束标记。
</script>
其次,你也缺少if和else语句的括号。
if (n1=="1"){
Price=12.5;
Stock=15;
}
else{
Price="40";
Stock="5";
}
希望它有所帮助!
BR, JoséSousa