2013-05-01 94 views
0

我有一個div,我可以插入單詞和輸入字段,用戶可以在輸入上鍵入單詞並保存它們以顯示在div「display_words」上。 現在我希望能夠從該分區刪除選定的話,我那些話分配一個動態的ID,它看起來像這樣:點擊事件選擇ID jquery

<div id="display_words"> 
    <div class="clhotpages" id="word1">word1</div> 
    <div class="clhotpages" id="word2">word2</div> 
</div> 

我有可以檢測他們點擊一個功能類「clhotpages」:

 $(".clhotpages").live('click', function() { 
     //GET ID TO REMOVE THAT WORD 
     alert("click"); 
     }); 

現在我希望能夠讓用戶從點擊事件中的div上移除單詞。

但我不知道如何從div中獲取ID,因爲ID是動態的。 感謝

回答

4

我建議:jQuery中被支撐

$('#display_words').on('click','div.clhotpages', function(e){ 
    var id = this.id; // or e.target.id; gets the id 
    $(e.target).remove(); // removes the word 
}); 

on()方法1.7+(和live()被棄用的1.7,並且如1.9移除)。在jQuery 1.7之前,推薦使用delegate()而不是live()

隨着delegate()以上的將被寫成:

$('#display_words').delegate('div.clhotpages', 'click', function(e){ 
    var id = this.id; // or e.target.id 
    $(e.target).remove(); 
}); 

參考文獻:

0

你可以做

$(".clhotpages").click(function() { 
    var currentID = $(this).attr("id"); 
    $(this).remove(); 
}); 
0

可以使用.attr() function提取特定屬性。

$(".clhotpages").live('click', function() { 
    $(this).attr('id'); 
}); 

這就是說,你不需要提取id以刪除元素。在點擊回調中,您可以使用$(this)變量來引用被點擊的實際元素。所以,你可以做這樣的事情 -

$(".clhotpages").live('click',function(){ 
    $(this).remove(); 
}); 

您可能還需要使用.on() function.live()的替代品。 .live()函數正在被棄用。使用.on(),你的代碼應該是這樣的:

$("#display_words").on('click','.clhotpages',function(){ 
    $(this).remove(); 
}); 

我假設#display_words元素存在的頁面加載時。

3

嘗試:

$("#display_words").on('click', '.clhotpages', function() { 
    var id = $(this).attr('id'); 
    alert("click"); 
}); 

.live(),取而代之的.on()被廢棄,完全的jQuery 1.9移除。更重要的是,當你動態添加元素時,你需要通過一個委託元素來綁定。

0
$(".clhotpages").click(function(){ 
    alert($(this).attr('id')); 
});