2015-09-10 94 views
0

我試圖創建一個消息列表,用戶可以在網站上的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(「點擊」,[...])。上動態創建的元素

DOCUMENTATION

+0

@Popnoodles你鏈接的問題也被標記爲重複:) –

+0

'ids'意味着是唯一 – dreamweiver

+0

@dreamweiver 我不好,我剛開始編碼兩個星期前,並監督該^^」 感謝您指出它出:) :) – sankai

回答

0
$(document).on('click', '#buttonid', function() { 

}); 

使用事件代表團使用:

$('#targetField').on("click",'.commentButton2', function(){ 

相反的:

$('.commentButton2').on("click", function(){ 

它應該工作。

+0

啊,現在我明白了!它工作finde,謝謝! – sankai

+0

快樂編碼隊友 – guradio

0
+1

它沒有爲我工作,甚至阻止靜態創建按鈕.. 但從佩卡得到了答案,謝謝:) – sankai