繁体   English   中英

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

[英]jquery class selector only registering events on first element of class

我目前正在使用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++;
};

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM