在列表中显示变量值?

时间:2014-04-10 17:51:17

标签: javascript html

<!doctype html>
<html>
<head>
<body>
<script>
  var a=8;
  var b=5;
  var c=8;
  var d=9;
</script>

<select size="5">
    <option value="1">"a" seats remaining</option>
    <option value="2">"b" seats remaining</option>
    <option value="3">"c" seats remaining</option>
    <option value="4">"d" seats remaining</option>
</select>
</body>
</html>

在列表中,而不是a,b,c,d,我可以显示变量的值,如8,5,8,9吗?

2 个答案:

答案 0 :(得分:2)

为您的选项提供ID以便于访问:

<select size="5">
    <option id="a" value="1"></option>
    <option id="b" value="2"></option>
    <option id="c" value="3"></option>
    <option id="d" value="4"></option>
</select>

然后你可以简单地做一些像

这样的事情
var a=8;
var b=5;
var c=8;
var d=9;

document.getElementById("a").innerHTML = a + ' seats remaining';
document.getElementById("b").innerHTML = b + ' seats remaining';
document.getElementById("c").innerHTML = c + ' seats remaining';
document.getElementById("d").innerHTML = d + ' seats remaining';

演示:http://jsfiddle.net/Ayp28/

答案 1 :(得分:0)

如果要替换,请尝试使用jQuery。

$("select > option").each(function() {
    var array = {"a":"8", "b":"5", "c":"8", "d":"9"};
    for (var val in array)
        this.text = this.text.split('"' + val + '"').join('"' + array[val] + '"');
});