在jquery中获取父级的属性
只是一个关于 jQuery 的简单问题。我是新手。当用户单击“span.fav”(星星)时,我如何获取“post_id”的值?我想要父级的值,而不是文档中的第一个值。我认为最接近的会起作用吗?
html和 jQuery 。
<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="fav">★</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>
到目前为止我拥有的
$(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);
});
});
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="fav">★</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);
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试:
区别在于最接近的内部:传递字符串而不是 jQuery 选择器。
Try:
The difference is inside closest: pass a string instead of jQuery selector.
只需找到父级,然后从中进行后续搜索:
Just find the parent, then do subsequent searches from that:
您应该找到最接近的表单并从表单中输入名为 post_id
you should find closest form and input named post_id from form