[英]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.