jquery类选择器仅在类的第一个元素上注册事件

时间:2012-03-14 11:12:28

标签: javascript jquery html jquery-plugins

我目前正在使用jquery中的表单字段荧光笔,到目前为止它的工作原理除了它只适用于表单的第一行,其余的字段没有注册我的焦点事件,以便我可以应用焦点格式  我目前正在使用以下jquery代码

    var debug = false;




    $(function(){

        $(".email-form tbody:last").AddFormLineToTable();

        $("#do-add-row").click(function () {

            if(debug)
            {
                alert("serialize click eventhandler fired");
            }

            $(".email-form tbody:last").AddFormLineToTable();
        });



        $(".does-focus-highlight").focusin(function(e){

            $(e.target).addClass("focus-highlight");
            if(debug){alert('field did focus');}
        });
        $(".does-focus-highlight").focusout(function(e){
            $(e.target).removeClass("focus-highlight");
            if(debug){alert('field did blur');}

        });


        $("#do-serialize").click(function(){
          if(debug)
          {
              alert("serialize click eventhandler fired");
          }
           var jsn = $("#contact-form").serializeArray();
        $("#serialize-target").val(JSON.stringify(jsn,null,2));



        });



    });

有什么东西我没有抓住这些额外的事件 如果这也会产生影响,那么不会以不同方式生成未触发的表单字段 正在生成如下

    var lineCount = 0;

jQuery.fn.AddFormLineToTable = function() {
    var o = $(this[0]);
    o.append('<tr id="contact-'+lineCount+'">' +
        '<td>Name: <input class="does-focus-highlight" id="contact-name-'+lineCount+'" name="contact-name-'+lineCount+'" type="text" required="required" /></td>' +
        '<td>Email: <input class="does-focus-highlight" id="contact-email-'+lineCount+'" name="contact-email-'+lineCount+'" type="email" required="required" /></td>' +
        '</tr>');

    lineCount++;
};

1 个答案:

答案 0 :(得分:0)

.click()仅将事件绑定到调用.click()时存在的元素。如果您希望为稍后创建的元素处理事件,请使用.on().live(),具体取决于您使用的jQuery版本。阅读非常有用的信息here

相关问题