如何更换该<选择>使用jquery的元素? [英] How do i replace this <select> element using jquery?

查看:244
本文介绍了如何更换该<选择>使用jquery的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在形式的元素。

<select name="states" disabled="disabled" size="10" id="select-states"><optgroup label="Choose State &raquo;&nbsp;">Choose State</optgroup></select>

我想用新的&LT替换上面的选择元素;选择&GT; 我从阿贾克斯获得

$.ajax({
    type: 'POST',
    url:  'process.php',
    data: 'countryId='+countryId,
    success: function(msg){
        if(msg == 0) {
            //Query returned empty.
        } else {
            //Query Has values.
            $('#select-states').html(msg);
        }
    }
});

例如上述的Ajax请求给我回了下面的HTML。

for example the above Ajax Request gives me back the following HTML.

<select name="states" size="10" id="select-states">
    <optgroup label="Choose State">Choose State</optgroup>
    <option value="36">First State</option>
    <option value="37">Second State</option>
    <option value="38">Third State</option>
    <option value="39">Fourth State</option>
</select>

语法 $('#选择 - 国家)HTML(MSG); 似乎并不被正确地更换内容&LT;选择&GT; 元素。但是如果我使用div取代它能够正常工作。这是正确的语法替换&LT;选择&GT; 元素

Syntax $('#select-states').html(msg); does not seems to be replacing the content correctly in <select> element. however if i replace it with div it works properly. which is the correct syntax for replacing the <select> element

推荐答案

您接近。只要改变这一行:

You were close. Just change this line:

$('#select-states').html(msg);

要:

$('#select-states').replaceWith(msg);

你拥有了它,现在它会插入新的选择到老,你会得到一些奇怪的HTML有两个元素使用相同的ID,并直接在另一个选择方式,如:

The way you have it right now it will insert your new select into the old one and you'll get some weird html with two elements with the same id and a select directly inside another, like:

<select name="states" disabled="disabled" size="10" id="select-states">
    <select name="states" size="10" id="select-states">
        <optgroup label="Choose State">Choose State</optgroup>
        <option value="36">First State</option>
        <option value="37">Second State</option>
        <option value="38">Third State</option>
        <option value="39">Fourth State</option>
    </select>
</select>

这篇关于如何更换该&lt;选择&GT;使用jquery的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆