2013-05-30 226 views
0

我正在使用jQuery编写一个应用程序,其中当单击按钮时,会生成一个选择框并将其附加到行中。只要选择的变化,它应该触发更改事件,但使用.on("change", function() {});不工作:jQuery .on()不会触发任何事件

代码:

<!DOCTYPE html> 
<html> 
    <head> 
     <title>HTML5-Template</title> 
     <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
     <style type="text/css"> 
      html, body 
      { 
      } 

      input,select { 
       border: 1px solid #404048; 
       padding: 4px; 
      } 
     </style> 
     <script type="text/javascript" src="../JavaScript/JQuery/jquery-1.9.1.js"></script> 
     <script type="text/javascript"> 
      $(document).ready(function() { 
       $("#cmdCreateRow").click(function() { 
        var row = $("<div />") 
        .css("font", "normal 12px Verdana") 
        .css("padding", "8px") 
        .css("display", "inline-block") 
        .css("background", "#F0F0F8") 
        .css("border", "1px solid #A0A0A8") 
        .css("margin", "2px"); 

        var types = [ 
         "Local", 
         "Remote", 
         "(Custom)" 
        ]; 

        var type = $("<select />").attr("class", "member-type"); 
        for(var i in types) { 
         type.append($("<option />").val(types[i]).text(types[i])); 
        }; 

        row.append(type); 

        $("#Container").append(row).append($("<br />")); 
       }); 

       $(".member-type").on("change", function() { 
        alert("changed"); 
       }); 
      }); 
     </script> 
    </head> 
    <body> 
     <input type="button" id="cmdCreateRow" value="Create Row" /> 
     <div id="Container"> 
     </div> 
    </body> 
</html> 

任何想法就是我做错了吗?

回答

9

由于$(".member-type")在你做绑定时是空的,你什么也没做。

变化

$(".member-type").on("change", function() { 
     alert("changed"); 
}); 

$(document).on("change", ".member-type", function() { 
     alert("changed"); 
}); 

或这是因为#container的元素是静态的:

$("#Container").on("change", ".member-type", function() { 
     alert("changed"); 
}); 
+0

工作......谢谢! :-) – series0ne

+1

我爱你回答这些社区维基。好家伙Dystroy FTW。 – rlemon

1

试试这个:

$(document).on("change", ".member-type", function() { 
    //Code 
}); 

这是替代:jQuery的“活”,请参阅:http://api.jquery.com/live/

-

“上”的方法经常将仅适用于已在DOM元素提供工作。