2013-11-26 42 views
1

我的html:jQuery的按類別確定元素ID

<a href="#" class="small button" id = "spare_approve_button_<?php echo $i; ?>">approve</a> 
<a href="#" class="small button" id = "spare_return_button_<?php echo $i; ?>">return</a> 

按鈕被環創建和我從來不知道我有多少按鈕將只有每一個都會有不同的ID。

我想,以確定被點擊,我試過了按鈕的ID:

$("a.small.button").click(function(){ 
     var button_id = this.id; 
     alert(button_id); 
}); 

一個按鈕被按下時,警告甚至不顯示這樣看來它不會檢測我的點擊。 Firefox控制檯顯示沒有錯誤。也許$("a.small.button")是錯的,但它應該是什麼?

+1

嘗試'$( 'a.button')' –

+2

@MarkWalters沒有。他是對的 –

+3

似乎在這裏工作:http://jsfiddle.net/VjENP/。 –

回答

2

也許你的JavaScript代碼執行得太早。試試這個:

$(function() { 
    $("a.small.button").click(function(){ 
     var button_id = this.id; 
     alert(button_id); 
    }); 
}); 

如果按鈕是在頁面中由javascript後者創建的,則必須在此之後執行您的代碼。或者你可以使用上的按鈕的父on jQuery函數:

$(function() { 
    // You can use a more specific parent. 
    $(document).on('click', 'a.small.button' function() { 
     var button_id = this.id; 
     alert(button_id); 
    }); 
});