简体   繁体   中英

A part of script in js file worked correctly with firebug console but not worked in page

I am really confusing, I have a js file with a lot of scripts, all of them worked correctly and I just add new lines:

$('.RemoveE').click(function () {
    alert('yap');
});

but that not worked, I test it with firebug and every things is OK, also I try another browsers that not worked either, I must mention that I add new button with CSS class ="ReomoveE button red" by script, this is a part of my js include new lines and add button:

// <reference path="../jquery-1.7.1.js" />
$(document).ready(function() {

    $('.RemoveE').click(function() {
        alert('yap');
    });

    //Add new Addable div
    $('.AddNewE').click(function() {

        var Target = $('.Addable:first');
        var TargetId = $(Target).attr('id');
        var Count = $('.Addable#' + TargetId).size();
        var CloneTarget = $(Target).clone();
        CloneTarget.find('input').val('');
        CloneTarget.insertAfter('.Addable:last');
        var TargetName = $(Target).find('input').attr('name');
        var CloneName = TargetName + '[1]';
        TargetName = TargetName + '[0]';
        $(Target).find('input').attr('name', TargetName);
        $(Target).find('span[class*="field-validation"]').attr('data-valmsg-for', TargetName);
        $(CloneTarget).find('input').attr('name', CloneName);
        $(CloneTarget).append($('<input type="button" class="RemoveE button red" value="remove" />'));

        (function($) {
            $.fn.updateValidation = function() {
                var form = this.closest("form").removeData("validator").removeData("unobtrusiveValidation");
                $.validator.unobtrusive.parse(form);
                return this;
            };
        })(jQuery);

        $(Target).updateValidation();
        $(CloneTarget).updateValidation();
    });
    ...
});​

So what do you think? Where is the problem, why all functions worked correctly, but this new one no?

You added the handler before the element existed:

$('.RemoveE').click(function() {
    alert('yap');
});

//then later

$(CloneTarget).append($('<input type="button" class="RemoveE button red" value="remove" />'));

Try:

Adding the handler on creation:

var newInput = $('<input type="button" class="RemoveE button red" value="remove" />')

newInput.click(function(){
    alert('yap');
});

$(CloneTarget).append(newInput)

or delegation with on()

$(parent_of_RemoveE).on('click','.RemoveE',function() {
    alert('yap');
});

You need to use .on() or .delegate() so it can listen to any new button that you created dynamically

See the sample code here

HTML

<div id='test'></div>​​​​​​​​​​​​​​​​​

JQUERY

​$(document).ready(function() { 
    $('#test').on('click','.removeE', function() {
     alert('yap');
    });

    $('#test').append('<input type="button" class="removeE" value="test"/>');
});​

you can see the example here

What @Joseph said basically. I commented your code bit to point out some things worth noting.

$(document).ready(function () {

    $('.RemoveE').click(function () {
        alert('yap');
    });

    //Add new Addable div
    $('.AddNewE').click(function () {

        var Target = $('.Addable:first');
        var TargetId = $(Target).attr('id'); // Double wrapping in jQuery

         // ID are unique, selector makes little sense,
         // and `length` is preferable to `size()`
        var Count = $('.Addable#' + TargetId).size();
        var CloneTarget = $(Target).clone(); // Double wrapping in jQuery
        CloneTarget.find('input').val('');
        CloneTarget.insertAfter('.Addable:last');
        var TargetName = $(Target).find('input').attr('name'); // Double wrapping in jQuery

        // This seems a bit verbose...
        var CloneName = TargetName + '[1]';
        TargetName = TargetName + '[0]';
        $(Target).find('input').attr('name', TargetName); // Double wrapping in jQuery
        $(Target).find('span[class*="field-validation"]').attr('data-valmsg-for', TargetName); // Double wrapping in jQuery
        $(CloneTarget).find('input').attr('name', CloneName); // Double wrapping in jQuery
        $(CloneTarget).append($('<input type="button" class="RemoveE button red" value="remove" />')); // Double wrapping in jQuery
        // end verbosity

        (function ($) {
            $.fn.updateValidation = function () {
                // Don't need to chain `removeData()` twice,
                // as of jQuery 1.7 you can pass a list
                var form = this.closest("form").removeData("validator").removeData("unobtrusiveValidation");
                $.validator.unobtrusive.parse(form);
                return this;
            };
        })(jQuery);

        $(Target).updateValidation(); // Double wrapping in jQuery
        $(CloneTarget).updateValidation(); // Double wrapping in jQuery
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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