我正在我的網站上開發一些 jQuery。已經制定了使用新輸入創建新容器的邏輯,但洗掉按鈕不起作用。有什么提示或路徑嗎?
var i = 0;
$("#addAula").click(function() {
i ;
$("#newAula").append('<div id="containerAula' [i] '"> <div > <label >Título</label> <input type="text" id="titulo_aula' [i] '" required> </div> <div > <label >Video ID</label> <input type="text" id="video_id' [i] '" required> </div> <div > <button id="removeAula' [i] '"> X </button> </div> <p ></div>');
});
$("#removeAula" i).click(function() {
$("#containerAula" i).remove(); //where i'm trying to reach the delete action
});
<div id="newAula">
<div class="inline-flex" id="containerAula0">
<div class="inline-block w-full mr-2">
<label class="text-sm font-bold text-center uppercase opacity-70">Título</label>
<input type="text" name="titulo" class="w-full p-3 mt-2 mb-4 rounded bg-slate-200" required>
</div>
<div class="inline-block ml-2">
<label class="text-sm font-bold uppercase opacity-70">Video ID</label>
<input type="text" name="video_id" class="w-full p-3 mt-2 mb-4 rounded bg-slate-200" required>
</div>
<div class="inline-block mt-10 ml-2">
<button id="removeAula0" class="h-8 px-3 font-bold duration-300 ease-in-out rounded cursor-pointer text-newwhite bg-red" type="button">
X
</button>
</div>
<p class="my-3">
</p>
</div>
</div>
<button id="addAula" class="px-6 py-3 my-2 font-bold duration-300 ease-in-out rounded cursor-pointer text-newwhite bg-lightgreen" type="button">
Aula
</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
圖片:

很抱歉任何菜鳥的錯誤,感謝您的時間
uj5u.com熱心網友回復:
洗掉偵聽器使用全域變數i,每次添加另一個 DIV 時都會遞增,而不是創建處理程式時的值。
您需要使用保存在閉包中的區域變數。
var i = 0;
$("#addAula").click(function() {
i ;
$("#newAula").append('<div id="containerAula' [i] '"> <div > <label >Título</label> <input type="text" id="titulo_aula' [i] '" required> </div> <div > <label >Video ID</label> <input type="text" id="video_id' [i] '" required> </div> <div > <button id="removeAula' [i] '"> X </button> </div> <p ></div>');
let cur = i;
$("#removeAula" i).click(function() {
$("#containerAula" cur).remove();
});
});
uj5u.com熱心網友回復:
我認為你應該嘗試這樣的事情
<script>
$(".removeAula").click(function(){
$(this).parent('.containerAula').remove();
});
</script>
您需要通過將一個類添加到每個洗掉按鈕(例如 removeAula)和每個容器(containerAula)中來更改您的 html,選擇每個洗掉按鈕并為其添加一個事件偵聽器,在該偵聽器中您只需查找其父級單擊的按鈕并將其洗掉。
我認為它應該作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/463883.html
