簡體   English   中英

確定在jquery中一組相似元素中單擊了哪個元素

[英]Identify which element was clicked, among a set of similar elements, in jquery

我有一個包含帖子的HTML頁面。

帖子定義為:

 <div class="post"> <p>...</p> <a href="#" class="post-react">Like</a> <input type="hidden" name="post-id" value="[postid]"> </div> 

一個頁面可以包含許多此類帖子。 當我單擊“喜歡”時,如何檢測單擊了哪個帖子元素的“喜歡”按鈕?

我在jQuery中嘗試了這個:

 $(function() { $('.post-react').bind('click', function() { $.getJSON('...', { post_id: $('input[name="post-id"]', this).val() }, function(data) { //something }); return false; }); }); 

$('input[name="post-id"]', this)正在尋找的輸入的后裔this ,但是輸入不是里面<a> ,它是同級

使用next()siblings()代替或遍歷post並使用find()

post_id: $(this).next().val()
// OR
post_id: $(this).siblings('input[name="post-id"]').val()
// OR
post_id: $(this).closest('.post').find('input[name="post-id"]').val()

請注意, bind()是一個非常古老的方法,已由on()取代

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM