2012-05-14 42 views
-2

讓說,我有5元從PHP查詢(所以它是動態的) 如下圖所示:jQuery的獲取ID或類從動態元素

element 1 class=element id=id_1 
element 2 class=element id=id_2 
element 3 class=element id=id_3 
element 4 class=element id=id_4 
element 5 class=element id=id_5 

我們ussulay通過了解他們的使用jQuery的事件ID,但在這種情況下,我們不知道它們的確切的ID

$("#id_3").click(function() 
{ 
    //in this case we have known we want to add event when we click id_3 
}); 

如何應對來自PHP查詢動態元素?
例如,我們如何知道我們點擊element 3id_3
我們必須填寫什麼$(????).click();
當我使用類,我怎麼能知道哪個ID我從點擊的類引用?

+0

未知的元素工作你可以放置標籤類型...例如,如果你的元素是div,你可以執行'$(「div」)。click()',然後在click事件中使用'this.id'來查看該元素是... – Chase

回答

0

如果它們都具有相同的類,那麼您可以使用類選擇器。然後使用this找到你以後的任何財產。

$('.element').click(
    $(this).prop('id'); 
); 
0

如果你想添加一個點擊只有那麼爲什麼不是添加到服務器端生成的HTML?

+1

這將違反嘗試從執行層(js)中分離表示層(html/css)的概念。我不會推薦這個。 – mrtsherman

0

您可以使用attribute starsWith選擇器& on在動態創建的元素上綁定事件。

$('body').on('click', '[id^=id]', function(e){ 

}); 
+0

是啊......我只是更新了... – 2012-05-14 02:33:54

1

在您的示例中的元素都具有相同的類,這樣你就可以建立基於該事件處理程序:

$(".element").click(function() { 
    // "this" refers to the clicked element 
    // this.id will be the id of the clicked element 
}); 

或者,如果這些元素是在通過Ajax加載感動態在初始頁面加載之後的某一時刻使用委派的事件處理程序:

$("somecontainerelement").on("click", ".element", function() { 
    // do something with this.id 
}); 

其中「somecontainerelement」理想的情況是動態元素被添加到元素,但可以只是document

+0

我喜歡這個解決方案。通過使用'on',他減少了頁面上綁定的事件處理程序的數量。這增加了你的JavaScript的效率。如果你不熟悉'on',那麼請閱讀。 http://api.jquery.com/on/。 =)! – mrtsherman

1

這是我能夠使其工作的唯一途徑。例如,如果你想獲得屬性ID或已被點擊的元素的值...

$("containerElem").on("click", "someElemID", function(evt) { 
    var getElemID = $(evt.target).attr("id"); 
    var getVal = $(evt.target).val(); 
}); 
0

這是veryusefull當我們與id或class

$(document).ready(function() { 
    // user this if element is div 
    $('div[id^="id_"]').on('click', function() { 
    alert($(this).attr('id')); 
    }); 
    // user this if element is input 
    $('input[id^="id_"]').on('click', function() { 
    alert(this.id); 
    }); 

});