Just a simple question about jQuery. I'm new at it. How would I get the value for "post_id" when the users clicks on "span.fav" (the star)? I want the parent's value, not the first one in the document. I think closest will work?
the html
<form action="index.php" method="post" accept-charset="utf-8">
<div class="hidden">
<input type="hidden" name="post_id" value="1000000019" />
<input type="hidden" name="xxxxxxx" value="xxxxxxxxxx" />
</div>
<p>
<span name="fav" class="开发者_如何学JAVAfav">★</span>Post message here...<span class="author">by Thomas Quantas</span>
</p>
</form>
<form action="index.php" method="post" accept-charset="utf-8">
<div class="hidden">
<input type="hidden" name="post_id" value="1000000020" />
<input type="hidden" name="xxxxxxx" value="xxxxxxxxxx" />
</div>
<p>
<span name="fav" class="fav">★</span>Post message here...<span class="author">by Thomas Quantas</span>
</p>
</form>
the jQuery I have so far.
$(document).ready(function(){
$("span.fav").bind('click', function() {
//var test = $(this).parent();
//var test = $(this).closest();
var hidden_id = $(this).closest($("input[type='hidden']").attr('value'));
var hidden_id = $("input[type='hidden']").attr('value');
alert(hidden_id);
});
});
Try:
var hidden_value = $(this).closest('form').find('input:hidden[name="post_id"]').attr('value');
alert(hidden_value);
The difference is inside closest: pass a string instead of jQuery selector.
Just find the parent, then do subsequent searches from that:
$('span.fav').click(function(){
var rel = $(this).parentsUntil('form').parent();
var hidden_id = $(rel).find("input[name='post_id']").val();
});
you should find closest form and input named post_id from form
var hidden_id = $(this).closest("form").find("input[name='post_id']").val();
精彩评论