替换选择框中的值

时间:2012-10-05 14:49:34

标签: javascript html

我正在尝试将 CLOSED 的值重新写入 TESTING 。注意,动态填充选择框。我的代码如下,但它没有产生预期的结果。

<html>    
     <head>   
           <script type="text/javascript">
                 window.onload = function() { loadit() }    
                 function loadit(){
                       var x = new Array()
                       x[0] = ""
                       x[1] = "ACTIVE"
                       x[2] = "ON HOLD"
                       x[3] = "CLOSED"

                       for (i=0; i<x.length; i++) 
                       { 
                              document.getElementById('d1').options[i]=new Option(x[i], i) 
                       }
                 }

                 function changeit() {
                       var el = document.getElementById("d1");
                       for(var i=0; i < el.options.length; i++)
                       {
                               if(el.options[i].value == "CLOSED")
                               {
                                     el.options[i].value = "TESTING";
                                     el.options[i].innerText = "TESTING";        
                               } 
                       }
                 }
             </script>
       </head>
       <body>
             <select name="d1" id="d1" style="width: 200px;"></select>
             <p><a href="javascript:changeit()">change</a></p> 
       </body>
</html>

3 个答案:

答案 0 :(得分:2)

了解如何创建选项

document.getElementById('d1').options[i] = new Option(x[i], i)

该值是一个数字,因此以下检查永远不会成立

 if(el.options[i].value == "CLOSED"){

您可以将其更改为.text

if (el.options[i].text== "CLOSED") {

或者您可以更改选择

的内容
document.getElementById('d1').options[i] = new Option(x[i], x[i]);

答案 1 :(得分:0)

你的值是0,1,2,3而不是文本,所以在你的循环中它应该是:

for(var i=0; i < el.options.length; i++){
    if(el.options[i].value == "3"){
        el.options[i].value = "3";
        el.options[i].innerText = "TESTING";        
    } 
}

答案 2 :(得分:0)

值为0,1,2等,因此您需要将代码更改为以下内容。

<html>

<head>

<script type="text/javascript">

window.onload = function() { loadit() }

function loadit(){
var x = new Array()
    x[0] = ""
    x[1] = "ACTIVE"
    x[2] = "ON HOLD"
    x[3] = "CLOSED"

    for (i=0; i<x.length; i++) { document.getElementById('d1').options[i]=new Option(x[i], i) }
}

function changeit() {

var el = document.getElementById("d1");
for(var i=0; i < el.options.length; i++)
    {
    if(el.options[i].value == "3")
        {
            el.options[i].value = "3";
            el.options[i].innerText = "TESTING";
        }
    }






}

</script>


</head>

<body>

<select name="d1" id="d1" style="width: 200px;"></select>

<p><a href="javascript:changeit()">change</a></p>

</body>

</html>