0

我将元素动态添加到 div 标签。之后我想在这个新添加的元素上执行点击事件。但它不起作用。

下面是代码。

$(document).ready(function () {
    $('#login-option').click(function () {

        $.ajax({
            url: "http://localhost/cgi-bin/login_form.pl",
            type: "GET",
            dataType: "html",
            //expect html to be returned
            // script call was *not* successful
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('div#proper-form').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", errorThrown: " + errorThrown);

                alert("script error");
            },
            // error 

            // script call was successful 
            success: function (response) {
                $("div#proper-form").html('<b id="testid"> testing</b>');
            }
        });

        $('div#proper-form').fadeIn(5000);
        return false;
    });

    $('div#proper-form').on('click', '#testid', function () {
        alert("working as expected");
    });
});

添加了新元素,但单击不起作用。可以请帮助我找出这里有什么问题。

任何帮助都会有很大的帮助。

谢谢

4

2 回答 2

0

尝试使用

    $('#testid').bind('click', function() {
....
}
于 2013-09-28T04:50:29.243 回答
0

你好请注意下面的代码并测试它

   $(document).ready(function(){
    $('#login-option').click(function () {

    $.ajax( {
        url: "http://localhost/cgi-bin/login_form.pl",
        type: "GET",
        dataType: "html", //expect html to be returned

        // script call was *not* successful
        error: function(XMLHttpRequest, textStatus, errorThrown) { 
          $('div#proper-form').text("responseText: " + XMLHttpRequest.responseText 
            + ", textStatus: " + textStatus 
            + ", errorThrown: " + errorThrown);

          alert ("script error");


        }, // error 


        // script call was successful 

        success : function(response)
        {
            $("div#proper-form").html('<b id="testid"> testing</b>' ); 
            $('#testid').bind('click', function () {
               alert ("working as expected"); 
            });
        }
    });


    $('div#proper-form').fadeIn(5000);
    return false;
    });
});
于 2013-09-28T04:56:39.877 回答