我有以下两个功能,使用onchange
从下拉菜单中获取输入 <script>
current_fin = "none";
current_mat = "Pine";
// Pass the current selection into a variable to use.
function getMaterial()
{
var mat = document.getElementById("dropdownone");
var current_mat = mat.options[mat.selectedIndex].text;
$("#price").html("Material is: " + current_mat + "<br/>" +"Finish is: " + current_fin);
}
function getFinish()
{
var fin = document.getElementById("dropdowntwo");
var current_fin = fin.options[fin.selectedIndex].text;
$("#price").html("Material is: " + current_mat + "<br/>" +"Finish is: " + current_fin);
}
</script>
所有这一切都是将所选内容的值写入div #price。现在问题出现在我改变一个然后另一个。如果我在两个框之间切换,变量将恢复为默认值none和pine。我希望他们保留函数之外的值,所以如果我将box 1切换到oak,它会保持不变,直到我将其切换回来。我有一种感觉,我在这里有范围问题,但不知道如何继续。我将包含HTML以供参考。
<select name="material" id="dropdownone" onchange="getMaterial()">
<option>Pine</option>
<option>Oak</option>
<option>Walnut</option>
<option>Plastic</option>
</select>
<select name="finish" id="dropdowntwo" onchange="getFinish()">
<option>None</option>
<option>Finished</option>
</select>
<input type="submit" value="Submit To Cart">
<div id=price>
</div>
答案 0 :(得分:3)
<script>
var current_fin = "none";
var current_mat = "Pine";
// Pass the current selection into a variable to use.
function getMaterial()
{
var mat = document.getElementById("dropdownone");
current_mat = mat.options[mat.selectedIndex].text;
$("#price").html("Material is: " + current_mat + "<br/>" +"Finish is: " + current_fin);
}
function getFinish()
{
var fin = document.getElementById("dropdowntwo");
current_fin = fin.options[fin.selectedIndex].text;
$("#price").html("Material is: " + current_mat + "<br/>" +"Finish is: " + current_fin);
}
当您在函数内部编写var current_mat
时,它会覆盖全局current_mat
。
答案 1 :(得分:0)
<!DOCTYPE html>
<html>
<head>
<script>
current_fin = "none";
current_mat = "Pine";
function getMaterial()
{
var mat = document.getElementById("dropdownone");
var current_mat = mat.options[mat.selectedIndex].text;
var fin = document.getElementById("dropdowntwo");
var current_fin = fin.options[fin.selectedIndex].text;
document.getElementById("price").innerHTML="Material is: " + current_mat + "<br/>" +"Finish is: " + current_fin;
}
function getFinish()
{
var fin = document.getElementById("dropdowntwo");
var current_fin = fin.options[fin.selectedIndex].text;
var mat = document.getElementById("dropdownone");
var current_mat = mat.options[mat.selectedIndex].text;
document.getElementById("price").innerHTML="Material is: " + current_mat + "<br/>" +"Finish is: " + current_fin;
}
</script>
</head>
<body>
<select name="material" id="dropdownone" onchange="getMaterial()">
<option>Pine</option>
<option>Oak</option>
<option>Walnut</option>
<option>Plastic</option>
</select>
<select name="finish" id="dropdowntwo" onchange="getFinish()">
<option>None</option>
<option>Finished</option>
</select>
<input type="submit" value="Submit To Cart">
<div id="price">
</div>
</body>
</html>