我試圖創建一個消息列表,用戶可以在網站上的textarea中鍵入並使用他自動創建的每個消息的按鈕刪除它們中的任何一個。 我的想法是,我創建了一個div,首先將用戶的消息放入,然後預先添加與div相同ID的按鈕;這樣我調用按鈕的ID並刪除具有相同ID的所有元素。使用jQuery/JS創建的按鈕,請不要點擊
<script>
var theButtonId = 1;
$(document).ready(function() {
$('#commentButton1').click(function() {
var toAdd = $("textarea#commentTextarea1").val(); //Content to add
var theId = "dieButtons"+theButtonId.toString(); //creating unique ID
// Adding first Div
$('#targetField').append(
$('<div />', {
id: theId,
}));
// Adding content
$('#'+theId).append(
$('<div />', {
text: toAdd
}));
//(-----1-----)Adding Button
$('#'+theId).prepend(
$('<button />', {
type: 'button',
id: theId,
class: 'commentButton2',
text: "-"
}));
theButtonId++;
});
});
//Button Command
$(document).on("ready", function(){
//(-----2-----)
$('.commentButton2').on("click", function(){
var thisId = $(this).attr("id");
$("#"+thisId).remove();
});
});
</script>
它完美地列出了#textfield 元件我直接在其中刪除某些的div,以及本身使用上面的代碼我的HTML代碼添加一個按鈕。這就是爲什麼我知道問題是(----- 1 -----)中創建的按鈕不對(----- 2 -----)
中的命令作出反應我已經嘗試創建一個輸入類型按鈕,並把一個.click函數,而不是.on(「點擊」,[...])。上動態創建的元素
@Popnoodles你鏈接的問題也被標記爲重複:) –
'ids'意味着是唯一 – dreamweiver
@dreamweiver 我不好,我剛開始編碼兩個星期前,並監督該^^」 感謝您指出它出:) :) – sankai