[英]javascript event not processing script
我在我的javascript上遇到了一個尷尬的問題,基本上我已經編寫了以下javascript來刪除我頁面中動態添加的li標簽,但它沒有處理,javascript是:
$(document).ready(function(e)
{
$(".close").on("click", this, function()
{
$(this).closest("li").remove();
var panelId = $(this).closest('li').attr('href');
// $(this).closest('#content').remove();
// $('#tab1').remove();
$('#nav-tabs a:last').tab('show');
$('#close1').on('click',this, function()
{
$('.tab1').remove();
$('#nav-tabs a:last').tab('show');
})
$('#close2').on('click',this, function()
{
$('.tab2').remove();
$('#nav-tabs a:last').tab('show');
})
$('#close3').on('click',this, function()
{
$('.tab3').remove();
$('#nav-tabs a:last').tab('show');
})
})
if(counter <= 1){
counter = 1;
}else {
counter--;
}
return false;
})
});
問題是當i /用戶點擊.close [具有關閉類的按鈕]時,這個javascript什么都不做,即使它應該刪除最近的li標簽; 此外,當我在添加javascript [javascript添加li標簽]粘貼這個開始工作!
問題是您先刪除li
然后嘗試讀取其中一個屬性。
在完成需要訪問它或其屬性的所有內容之后,您需要刪除li
。
即
$(document).ready(function(e) {
$(document).on("click", ".close", function() {
var panelId = $(this).closest('li').attr('href'); // get the href first
$(this).closest("li").remove(); // now delete the li
...
});
});
嘗試這個:
$(document).ready(function(e)
{
$(document).on("click", ".close", function()
{
$(this).closest("li").remove();
var panelId = $(this).closest('li').attr('href');
// $(this).closest('#content').remove();
// $('#tab1').remove();
$('#nav-tabs a:last').tab('show');
$(document).on('click','#close1', function()
{
$('.tab1').remove();
$('#nav-tabs a:last').tab('show');
})
$(document).on('click','#close2', function()
{
$('.tab2').remove();
$('#nav-tabs a:last').tab('show');
})
$(document).on('click','#close3', function()
{
$('.tab3').remove();
$('#nav-tabs a:last').tab('show');
})
})
if(counter <= 1){
counter = 1;
}else {
counter--;
}
return false;
})
});
您在讀取id
之前刪除了li
,因此panelId
將是undefined
,您還必須使用基於事件委派的事件hadndling
$(document).ready(function(e) {
$('#close1').on('click', this, function() {
$('.tab1').remove();
$('#nav-tabs a:last').tab('show');
})
$('#close2').on('click', this, function() {
$('.tab2').remove();
$('#nav-tabs a:last').tab('show');
})
$('#close3').on('click', this, function() {
$('.tab3').remove();
$('#nav-tabs a:last').tab('show');
})
$(document).on("click", ".close", function() {
var panelId = $(this).closest('li').attr('href');
$(this).closest("li").remove();
$('#nav-tabs a:last').tab('show');
})
if (counter <= 1) {
counter = 1;
} else {
counter--;
}
return false;
})
最明顯的原因是綁定事件時,DOM中不存在.close
元素。 一個簡單的解決方案是使用event delegation
,也可以使用jQuery on()實現 。 換句話說,事件將綁定到另一個元素,即所需目標元素的父元素。 這樣,你就必須將事件綁定一次,而不必在運行時的每個新元素上重新綁定它。 例如
$(window).click('.close',yourCloseFunction);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.