简体   繁体   English

动态创建元素后分配点击事件

[英]Assign click event after an element was created dynamically

So, instead of having a form in the HTML, I decided to create the form on fly and append it to another element (in my case a <section> , but that will be an option in the near future). 因此,我决定不使用HTML中的表单,而是决定动态创建表单并将其附加到另一个元素(在我的情况下为<section> ,但这将是不久的将来的一种选择)。

I'm using this method: 我正在使用这种方法:

var formWrapper = ['<div class="content-login">','</div>'];

var form = [
    '<form name="login-form" class="login-form" method="post" action="#">',
        '<fieldset class="login-fields">',
            '<fieldset class="username-wrapper">',
                '<label for="username" class="user-img"><img src="assets/gfx/user.png" alt="Username" /></label>',
                '<input type="text" name="username" class="username" placeholder="Username" value="" autocomplete="off" />',
            '</fieldset>',
            '<fieldset class="password-wrapper">',
                '<label for="password" class="pass-img"><img src="assets/gfx/password.png" alt="Password" /></label>',
                '<input type="password" name="password" class="password" placeholder="Password" value="" autocomplete="off" />',
            '</fieldset>',
            '<fieldset class="login-wrapper">',
                '<button type="submit" name="login" class="login">Login</button>',
            '</fieldset>',
        '</fieldset>',
    '</form>'       
];

setTimeout(function () {
    $(formWrapper.join('')).appendTo('section').hide();
    $(form.join('')).appendTo('.content-login');
    $('.content-login').fadeIn('slow');
}, 1500);

This way I have a nice fade in effect and it will give me the opportunity to change whatever I want after I fully develop it. 这样,我的效果会很好,并且在我完全开发它之后,将有机会改变我想要的任何东西。

But my question is in fact the following: I have a form, so of course I will use Ajax to submit it, and I already have the script for that. 但是实际上我的问题是:我有一个表单,所以我当然会使用Ajax提交它,并且我已经有了该脚本。 The thing is now, when I click on the button, the .click event does not occur, it only takes me to the default action of the form which is "#" in my case. 现在的事情是,当我单击按钮时,不会发生.click事件,它只会带我进入表单的默认操作,本例中为“#”。 Why is that ? 这是为什么 ?

Here is the other part of the script, for a better understanding : 这是脚本的另一部分,可以使您更好地理解:

$('.login-form .login').click(function(){
    if($('input.username').val() == "" || $('input.password').val() == "")
    {
        console.log('Please enter Username & Password');
        $('.login-form').effect("shake", { distance: 40, times: 2 }, 100);
        return false;
    }
    else {  

        $('.login-fields').fadeOut();
        $('.login-form').spin("login", "#ffffff");      
        $.ajax
        ({
            type: 'POST',
            url: 'assets/class/login/process.php',
            dataType: 'json',
            data:
            {
                username: $('input.username').val(),
                password: $('input.password').val()
            },
            success:function(data)
            {
                if(!(data.lockdown == true)) {
                    if(data.error === true) {   
                        console.log(data.message);
                        $('.login-form').spin(false);
                        $('.login-fields').fadeIn();
                        $('.login-form').effect("shake", { distance: 40, times: 2 }, 100);
                    }
                        else {
                            console.log(data.message);
                            $('.login-form').spin(false);
                            $('.login-fields').fadeIn();
                            $('.content-login').fadeOut();

                            var structure = [
                                '<div class="after-login">',
                                    '<div class="inside">',
                                        '<div class="row-one">',
                                            '<h1>',data.message,'</h1>',
                                        '</div>',
                                        '<div class="row-two">',
                                            '<a class="cancel" href="',links.cancel,'?logout">Cancel</a>',
                                            '<a class="continue" href="',links.proceed,'">Continue</a>',
                                        '</div>',
                                    '</div>',
                                '</div>'
                            ];

                            setTimeout(function () {
                                $(structure.join('')).appendTo('section').fadeIn('slow');
                            }, 1500);

                        }
                }
                    else {
                        console.log(data.message);
                        $('.login-form').spin(false);
                        $('.content-login').fadeOut();

                        var structure = [
                            '<div class="system-lockdown">',
                                '<div class="inside">',
                                    '<div class="row-one">',
                                        '<h1>',data.message,'</h1>',
                                    '</div>',
                                    '<div class="row-two">',
                                        '<a class="back" href="',links.goback,'">Back</a>',
                                    '</div>',
                                '</div>',
                            '</div>'
                        ];

                        setTimeout(function () {
                            $(structure.join('')).appendTo('section').fadeIn('slow');
                        }, 1500);
                    }
            },
            error:function(XMLHttpRequest,textStatus,errorThrown)
            {
                console.log('A PHP error triggered this, check your PHP log file for more information');
            }
        });
        return false;
    }
});

$.click() will only work on elements that have been created before the handler was created. $.click()仅适用于在创建处理程序之前创建的元素。

Instead, use $.live() instead: 而是使用$.live()代替:

$('.login-form .login').live('click', function() {
    // Your code
});

If you're using jQuery 1.7 or above, you can also use $.on() in a similar way: 如果您使用的是jQuery 1.7或更高版本,则还可以通过类似的方式使用$.on()

$('.login-form .login').on('click', function() {
    // Your code
});

The preferred way to handle events with dynamically added content is with on() —or delegate , since you're on jQuery 1.6 处理带有动态添加内容的事件的首选方法是on()delegate ,因为您使用的是jQuery 1.6

$(document).delegate('.login-form .login', 'click', function(){
});

Note that this will listen to every single click anywhere in your document. 请注意,这将监听文档中任何位置的每次单击。 Ideally you'd like to identify some more narrow container from which all clicks will come, and listen to that . 理想情况下,您想确定一个更狭窄的容器, 所有点击都将来自该容器,然后听一下 So if all these clicks will be coming from your section, you'd do this 因此,如果所有这些点击都来自您的板块,则可以这样做

$("section").delegate('.login-form .login', 'click', function(){
});

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

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