如何使用 jQuery 找到最近的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3623103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find closest element with jQuery
提问by Steven
I have the following HTML code:
我有以下 HTML 代码:
<td>
<input type="text" size="40" value="" name="related_image" id="related_image">
<input type="button" class="button addImage" value="Get image url">
</td>
<td>
<input type="text" size="40" value="" name="alternative_image" id="alternative_image">
<input type="button" class="button addImage" value="Get image url">
</td>
I need to figure out which button I click, then add some text to the nearest input text field.
E.g. if I click the button in the first <td>
, then I need to input some text into related_image
text field.
我需要弄清楚我单击了哪个按钮,然后在最近的输入文本字段中添加一些文本。
例如,如果我点击第一个按钮<td>
,那么我需要在related_image
文本字段中输入一些文本。
I've tried with the followin jQuery, but it's not working:
我已经尝试使用以下 jQuery,但它不起作用:
jQuery('.addImage').click(function() {
var tmp = jQuery(this).closest("input[type=text]").attr('name');
alert(tmp);
});
(I'm just retrieving the inputs name for testing.)
(我只是检索用于测试的输入名称。)
I think I might have to use find
and / or siblings
. But I'm not quite sure how.
我想我可能必须使用find
和/或siblings
. 但我不太确定如何。
Any help appreciated.
任何帮助表示赞赏。
EDIT
编辑
I just managed to use this codeaddImageEvent = jQuery(this).prevAll("input[type=text]:first")
我只是设法使用此代码addImageEvent = jQuery(this).prevAll("input[type=text]:first")
Is using prevAll
a bad choice?
使用prevAll
是一个糟糕的选择吗?
回答by cletus
Try:
尝试:
var tmp = $(this).siblings(":text").attr("name");
The closest()
method you're using finds the closest ancestor, which is not what you want here.
closest()
您使用的方法会找到最近的祖先,这不是您在这里想要的。
回答by Nick Craver
.closest()
finds a parent, in this case you need .siblings()
, like this:
.closest()
找到一个父母,在这种情况下你需要.siblings()
,像这样:
jQuery('.addImage').click(function() {
var tmp = jQuery(this).siblings("input[type=text]").attr('name');
alert(tmp);
});
Or if the format is always consistent like your example, just use .prev()
, like this:
或者,如果格式始终与您的示例一致,只需使用.prev()
,如下所示:
jQuery('.addImage').click(function() {
var tmp = jQuery(this).prev().attr('name');
alert(tmp);
});
回答by Nathan Bubna
Here is a 'closest' implementation that aims at descendants instead of parents:
这是一个针对后代而不是父母的“最接近”的实现:
$.fn.nearest = function(selector) {
var nearest, node = this, distance = 10000;
node.find(selector).each(function(){
var n = $(this),
d = n.parentsUntil(node).size();
if (d < distance) {
distance = d;
nearest = n;
} else if (d == distance) {
nearest.add(this);
}
});
return nearest;
};