如何使用jQuery找到最接近的元素
我有以下HTML代码:
我需要找出我点击的按钮,然后将一些文本添加到最近的输入文本字段。
例如,如果我单击第一个
related_image
文本字段中输入一些文本。
我已尝试使用followin jQuery,但它不起作用:
jQuery('.addImage').click(function() { var tmp = jQuery(this).closest("input[type=text]").attr('name'); alert(tmp); });
(我只是检索输入名称以进行测试。)
我想我可能不得不使用find
和/或siblings
。 但我不太确定如何。
任何帮助赞赏。
编辑
我只是设法使用此代码
addImageEvent = jQuery(this).prevAll("input[type=text]:first")
使用prevAll
是一个糟糕的选择吗?
尝试:
var tmp = $(this).siblings(":text").attr("name");
您正在使用的closest()
方法找到最接近的祖先,这不是您想要的。
.closest()
找到一个父类,在这种情况下你需要.siblings()
,如下所示:
jQuery('.addImage').click(function() { var tmp = jQuery(this).siblings("input[type=text]").attr('name'); alert(tmp); });
或者,如果格式总是像您的示例一样,只需使用.prev()
,如下所示:
jQuery('.addImage').click(function() { var tmp = jQuery(this).prev().attr('name'); alert(tmp); });
这是一个“最接近”的实现,旨在为后代而不是父母:
$.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; };