gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:01:27 25 4
gpt4 key购买 nike

我在点击事件方面遇到了一些问题,我猜测正在发生,因为我点击的内容是在页面加载后附加的,这里是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com