remove()后选项仍然可见

时间:2012-09-05 04:23:28

标签: javascript jquery jquery-ui cordova jquery-mobile

大家好我有两个选择字段,如果用户选择选项值一,则首先在选择字段上然后在第二个选择字段中所有选项都可见但是如果它首先选择选项二,则选项二想要从选择ID中删除第二。以下是我的代码:

<script type="text/javascript">
 var index3,str;
</script>

<select id="first"  onchange="chk();">
<option value = "one">one</option>    
<option value = "two">two</option>    
<option value = "three">three</option>    
</select>

<select id="second">
<option value = "one">one</option>    
<option value = "two">two</option>    
<option value = "three">three</option>     
</select>


<script type="text/javascript">
function chk()
{
    index3 = document.getElementById("first");
    str= index3.options[index3.selectedIndex].value;

    alert("str:"+str);

    if (str=="two")
    {
          $("#second option[value='two']").remove();
    }

    else
    {
          if ( $("#second  option[value='two']").length == 0 )
         {

             $("#second").append('<option value="two">two</option>');
         }
    }
}
</script>

在小提琴中它工作正常here,但在移动问题上是:如果我从select id second中选择选项2,然后在第一个选择id中选择选项值2,那么第二个选择中也可以看到选项二id,如果我点击第二个选择id,那么只有它删除。但是在jsFiddle中它完美无缺。任何建议将不胜感激,提前致谢。

enter image description here

enter image description here

3 个答案:

答案 0 :(得分:1)

这里我已完成上述问题的完整垃圾箱。请通过演示链接。

演示 http://codebins.com/bin/4ldqp7p

<强> HTML

<select id="first">
  <option value = "one">
    one
  </option>

  <option value = "two">
    two
  </option>

  <option value = "three">
    three
  </option>

</select>

<select id="second">
  <option value = "one">
    one
  </option>

  <option value = "two">
    two
  </option>

  <option value = "three">
    three
  </option>

</select>

<强>的jQuery

$(function() {

    $("#first").change(function() {
        var optVal = $(this).val().trim();

        if (optVal == "two") {

            $("#second").find("option[value=" + optVal + "]").remove();
        } else {
            if ($("#second").find("option[value=two]").length <= 0) {

                $("<option value=\"two\">two</option>").insertAfter($("#second").find("option[value='one']"));

            }
        }
    });

});

演示 http://codebins.com/bin/4ldqp7p

答案 1 :(得分:0)

检查此Edit

$('#first').change(function() {
      $("#second option[value='" + $(this).val() + "']").remove();
});

答案 2 :(得分:0)

你的代码看起来有点奇怪。如果您打算在“第一个”中选中“第二个”项目,请尝试此更新:http://jsfiddle.net/NWbXt/58/

$(function() {
    var first = $('#first'),
        second = $('#second'),
        removed;

    first.change(function() {
        var selected = first.val();
        second.append(removed);  //.. add back old option
        removed = second.find('option[value="' + first.val() + '"]').remove();        
    }).trigger('change');
});​