【问题标题】:jQuery click event issues with appended list item附加列表项的jQuery单击事件问题
【发布时间】:2013-10-25 05:46:44
【问题描述】:

我在点击事件时遇到了一些问题,我猜这是因为在页面加载后我点击的是 jquery 和 jsfiddle

http://jsfiddle.net/PTHsY/

$(document).ready(function(){

// Adding a project
$('.project-btn').click(function(e){
    e.preventDefault();

    //grab the user input for the new project
    var project = $('.project-val').val();

    //Add the project to the list
    $('<li></li>').addClass(project).appendTo('.project-list');
    $('<a></a>').attr("href",project).text(project).appendTo('li.'+project);

    // create the div where the categories will go
    $('<div></div>').attr("id",project).appendTo('.category-wrapper');
    // hide the div untill it is called upon
    $('div#'+project).fadeOut(function(){
        $('<h1></h1>').text(project).css("text-align","center").appendTo('div#'+project);
        // add the input for the category div
        $('<input>').attr("type","text").addClass('category-val').appendTo('div#'+project);
        $('<input>').attr("type","submit").attr("value","Add Category").addClass("category-btn-"+project).appendTo('div#'+project);
        // add the ul
        $('<ul></ul>').attr("class","category-list").appendTo('div#'+project);
        // add the back button
        $('<p></p>').text("back").addClass('category-back').css("cursor","pointer").appendTo('div#'+project);
    });

    // clear the input search
    $('.project-val').val('');

}); 

$('a').click(function(e){
    e.preventDefault();
    selectedDiv = $(this).attr("href");
    alert("clicked");
    $('.project-wrapper').fadeOut(function(){
        $('div#'+selectedDiv).fadeIn();
    });
});
});  

我试图仅在单击添加的列表项后才显示隐藏的 div。由于某种原因,我在上面说了我的猜测,它不起作用。当单击任何锚元素但我没有得到响应时,我添加了一个“单击”警报

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    您需要使用event delegation 将事件分配给动态元素。使用jQuery's on() method 将点击事件添加到a 元素的非动态祖先,将a 选择器作为参数传入(在这种情况下,我使用了文档的body):

    $('body').on('click', 'a', function(e){
        ...
    });
    

    JSFiddle Demo.

    当提供selector 时,事件处理程序被称为委托。当事件直接发生在绑定元素上时,不会调用处理程序,而只会调用与选择器匹配的后代(内部元素)。 jQuery 将事件从事件目标冒泡到附加处理程序的元素(即从最内到最外的元素),并为匹配选择器的路径上的任何元素运行处理程序。

    【讨论】:

    • 谢谢 我必须在动态元素上使用“on”的原因是什么?
    • 我会尽快给你支票
    • @swsa 因为您的元素在该事件处理程序首次启动时不存在。您的事件处理程序没有分配给任何东西,因此在动态添加元素时不存在。在使用on() 时,我们将事件处理程序添加到body,它在添加元素之前就存在。
    • 我不想惹人厌烦,但如果我把我想做的事情详细发给你,我相信这对你来说很简单,你能帮我吗?
    • @swsa 恐怕我要睡觉了(这里是晚上 11 点),对不起!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 2012-08-16
    • 1970-01-01
    相关资源
    最近更新 更多