0

我正在尝试将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>
4

3 回答 3

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]);
于 2012-10-05T14:55:06.577 回答
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";        
    } 
}
于 2012-10-05T14:54:51.087 回答
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>
于 2012-10-05T15:06:49.127 回答