简体   繁体   English

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

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

im currently working on a form field highlighter in jquery and so far it works except it only works on the first line of the form and the rest of the fields do not register my focus events so that i may apply focus formatting i am currently using the following jquery code 我目前正在使用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));



        });



    });

is there something im missing to catch these additional events the form fields that are not firing are being generated dunamically as well if that makes a difference as well which are being generated as follows 是否会缺少一些东西来捕捉这些额外的事件,如果没有触发的表单域也会被动态生成,这也会产生差异,如下所示

    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() binds events only to elements that are existing at the time of calling .click() . .click()仅将事件绑定到调用.click()时存在的元素。 If you want the events to be handled for elements that are created later on, use .on() or .live() , depending on the version of jQuery you are using. 如果要为以后创建的元素处理事件,请使用.on().live() ,具体取决于所使用的jQuery版本。 Read the very helpful info here . 此处阅读非常有用的信息。

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

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