且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果它是动态生成的,如何更改下拉菜单中的选项?

更新时间:2022-06-26 00:19:25

演示

我给sel和按钮一个ID,并更改了对jQuery的dom访问权限

I gave the sel and the button an ID and changed the dom access to jQuery

我现在也使用"i"和"j"

I also use the "i" and "j" now

假设您要同步3个选择项,则代码可能如下所示

Assuming you wanted to syncronise the 3 selects, the code could look like this

$(function() {
  $("input[type=button][value=Add]").click(function(e) {
    e.preventDefault();
    for (var i=0,n=$('#sel').val();i<n; i++) {
      var newDiv = $("<div>").appendTo("#dropbox");
      for (var j=0;j<3;j++) {
        var id = "input"+i+"_"+j;
        $("<select>")
          .attr("id",id)
          .attr("name",id)
          .on("change",function() {
            // set all other select's value to this value
            $(this).siblings("select").val(this.value);
          })
          .append(
            $("<option>").val("0").text("Option 1"), 
            $("<option>").val("1").text("Option 2"))
          .appendTo(newDiv);
      } // j
      $("<input>")
          .attr("name", "input"+i+"_"+j)
          .appendTo(newDiv);
      $("<button>").text("Remove").appendTo(newDiv).click(function(e) {
        e.preventDefault();
        $(this).parent().remove();
      })
    } // i
  })
})​