jQuery 单击事件与附加列表项的问题

标签 jquery html

我在点击事件方面遇到了一些问题,我猜测正在发生,因为我点击的内容是在页面加载后附加的,这里是 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。由于某种原因,我在上面陈述了我的猜测,它不起作用。当单击任何 anchor 元素但我没有得到任何响应时,我添加了一个警报“已单击”

最佳答案

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

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

<强> JSFiddle Demo .

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

关于jQuery 单击事件与附加列表项的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19577287/

相关文章:

html - div 内有两张卡片,宽度不相等

php - 如何使用 MAX() 函数让 PHP 和 MySQL 返回一个整数?

javascript - Javascript 中值列表的动态验证

html - 悬停 CSS 时影响另一个 div

html - 添加了全局宽度我希望一个特定元素超过该宽度限制

javascript - 当 iOS 11 Webview 失去焦点时,HTML <select> 停止触发 onchange 或 onblur

jQuery:如何选择名称为 xyz 的下一个元素?

javascript - 如何打印出对象的所有属性

javascript - ajax InvalidStateError : An attempt was made to use an object that is not, 或不再可用

javascript - 使用 javascript 测试错误的 reCAPTCHA 站点 key