dtoka218420 2013-07-31 06:23
浏览 54

无法在从jquery脚本添加的表单上运行jquery函数

I made a script that will create a login form if the user is not logged in. I've created the form with the html() function (let me know if there is a better alternative). So far this is working fine and the form will log the user in once a proper username/pass is given.

My problem is that I can't then run jquery functions on these newly added forms even if the code is added after the fact. For example, something like

$('#usernamefield').attr('value', 'login');

will do nothing. Obviously I'm doing something wrong but I'm not sure what. I've provided the relevant code below (the section on submitting to the server is removed). All this code does is creates the form when the user is not logged in. Then I just want an alert to pop up when I click on the username form, but obviously that part doesn't work in this example.

//This will create the login form and will submit data to the server and perform an action based on the results
var loginForm = function(){
    $('.logindiv').html("<!-- Form Code Start --><form id='login' method='post' accept-charset='UTF-8'><input type='hidden' name='submitted' id='submitted' value='1'/><div><span class='error'></span></div><label for='username' >UserName*:</label><input type='text' name='formusername' id='formusername' value='' maxlength='50' /><span id='login_username_errorloc' class='error'></span><label for='password' >Password*:</label><input type='password' name='formpassword' id='formpassword' maxlength='50' /><span id='login_password_errorloc' class='error'></span><input type='submit' name='Submit' value='Submit' /></form>")
};

$(document).ready(function(){
    //Check Login and load appropriate apps based on result
    $.post('./reg_source/check_login.php', function(data)   { 
        //If the user is logged in then this section will run. Ugh double negatives!
        if (data !== "false") {
            getUserData(data);
            $('.logindiv').html("Welcome back, "+dbdata[4]+"! <br> <a href='reg_source/logout.php'>Logout</a> | <a href='profile.php'>Profile</a>");
        }
        //If the user is NOT logged in then this will run
        else if (data === "false")
        {
            loginForm();
            $('.registerdiv').html("<a href = 'register.php'>Register Here</a>");
        }
    });

    $('#formusername').click(function(){
        alert("You clicked me!");
    });

});
  • 写回答

6条回答 默认 最新

  • douzhan1238 2013-07-31 06:25
    关注

    You need to use event delegation, since the formusername element is added dynamically

    $(document).on('click', '#formusername', function(){
        alert("You clicked me!");
    });
    
    评论

报告相同问题?