用jQuery替换select

时间:2013-08-18 21:01:49

标签: jquery select

我正在尝试替换select元素。但是,不是用id“Base”替换select,而是在具有相同ID的select中生成新的select。我的代码的相关部分如下。您认为生成重复选择的部分是什么?搜索时可以在此站点看到此问题。 http://bahcalculator.org/nano/

<select class="base" id="Base" onChange="codeAddress2();">
    <option>Select State First...</option>
</select>

function getbases2(){
    var S=$('#search').val();
    $.post("getbases2.php", {S:S},
        function(data) {
            $('#Base').html(data);
        });
} 
//getbases2.php

$S=$_POST['S'];
$re=mysql_query(" SELECT * FROM state_bases WHERE Base='$S' ");
$ro=mysql_fetch_assoc($re);
extract($ro);

echo "
     <select class='base' id='Base' onchange='codeAddress2();'>
         <option>Select base</option>
    ";

$re=mysql_query(" SELECT Base FROM state_bases WHERE State='$State' ORDER BY Base ASC");
while ($ro=mysql_fetch_assoc($re)){
    extract($ro);
    if ($Base!=""){
    echo "
        <option
        ";
        if ($Base=="$S"){ echo " selected='selected' ";}
            echo " 
            >$Base</option>
        ";
    }
}
echo "
    </select>
    <script type='text/javascript'>
        $('#State').val('$State');
            codeAddress2();
    </script>
    ";

2 个答案:

答案 0 :(得分:1)

$.html()调用将更新元素的内容:它在select中插入'data'。 您应该使用$.replaceWith()代替:http://api.jquery.com/replaceWith/

答案 1 :(得分:1)

嗯,它正在按照你所说的去做 - 在#Base中生成<select>,这是一个<select>。如果您想要替换它,请尝试使用<select>覆盖顶部<div id="wrap-around"></div>