这个问题在这里已有答案:
我使用jQuery和Ajax创建了一个函数,用于将信息从单独的PHP文件附加到另一个文件。让我们调用目标文件“Homepage”和包含数据“Template”的文件。
所以我使用这个功能:
var box = $('#infoPageContainer'),
close = $('.arrow');
btn1.click( function(){
event.preventDefault();
if( box.hasClass( 'active' )){
box.removeClass( 'active' );
box.css( "width", "0%" );
$('#placeholder1').fadeOut(600);
setTimeout(function(){
$('#placeholder1').html("");
},1000);
} else {
box.addClass('active');
box.css( "width", "100%" );
$.ajax({
url: 'template/parts/Template.php',
success: function(data){
$('#placeholder1').html(data).fadeIn(600);
},
beforeSend: function(){
$('#placeholder1').html("loading").fadeIn(600);
}
});
}
});
要附加此数据:
<div class="mainImgContainer1 templateImgContainer"></div>
<div class="textContainer">
<img src="img/arrow-01.png" alt="arrow" class="arrow">
<div class="titleContainer"><h3>Veldopstellingen</h3></div>
<div class="textWrapper">
<h4>Dit is de titel</h4>
<p class="broodTekst">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
</div>
</div>
正如您所看到的,我使用了一个检查“Active”类的开关并运行相应的功能。然而,我想要的是删除附加数据的功能,该附加数据由附加的按钮触发(Img with Arrow class)。像这样:
close.click( function(){
event.preventDefault();
box.removeClass( 'active' );
box.css( "width", "0%" );
$('#placeholder1').fadeOut(600);
setTimeout(function(){
$('#placeholder1').html("");
},1000);
});
但是当我这样做时,即使该功能在我不使用附加对象作为触发器时也没有任何作用。我该怎么办?
jQuery在运行时只知道页面中的元素,因此添加到DOM的新元素无法被jQuery识别。要解决这个问题,请使用event delegation,将新添加的项目中的事件冒泡到DOM中的一个点,当jQuery在页面加载时运行时。许多人使用document
作为捕捉起泡事件的地方,但没有必要一直向前走DOM树。理想情况下you should delegate to the nearest parent existing at the time of page load.
在你的代码中它将是这样的:
$(document).on('click', close, function() {...