选择特定的最接近元素
我有以下 html :
<table id="objects">
<tr>
<td>
<input type="text" value="2" />
</td>
<td>
<a href="#" class="delete">link</a>
</td>
</tr>
<tr>
<td>
<input type="text" value="4" />
</td>
<td>
<a href="#" class="delete">link</a>
</td>
</tr>
</table>
当我单击锚标记时,我想选择最接近我的链接的 ,并获取它的值。我该怎么做?我正在尝试:
$('.delete').click(function(e){
e.preventDefault();
var val = $(this).closest('input').attr('value');
alert(val);
});
但没有任何运气。
I have the following html :
<table id="objects">
<tr>
<td>
<input type="text" value="2" />
</td>
<td>
<a href="#" class="delete">link</a>
</td>
</tr>
<tr>
<td>
<input type="text" value="4" />
</td>
<td>
<a href="#" class="delete">link</a>
</td>
</tr>
</table>
When I click anchor tag I'd like to select <input>
closest to my link, and get it's value. How can I do this ? I was trying :
$('.delete').click(function(e){
e.preventDefault();
var val = $(this).closest('input').attr('value');
alert(val);
});
but without any luck.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您查看最接近的文档,您会看到它说它找到了祖先..
您的情况下的输入不是
.delete
链接的祖先。您需要使用
.closest('tr')
向上移动,然后使用.find('input')
向下钻取以查找输入,因此
If you look at the documentation for closest you will see that it says that it finds ancestors ..
the input in your case is not an ancestor of the
.delete
link.You need to move up with
.closest('tr')
and then drill down to find the input with.find('input')
so
closest
函数的名称极具误导性:它实际上是返回的最近的祖先。正确的代码是:
我不建议将事件处理程序绑定到 alllllllll 锚标记;如果页面上有很多这样的元素,这将是低效的。相反,我强烈建议使用 delegate() 或 live() 代替。
这会将事件处理程序绑定到
table
(一次),然后使用 JavaScript 事件冒泡机制来检测与第一个参数中传递的选择器匹配的元素的单击(在本例中为删除按钮) )。The name of the
closest
function is extremely misleading: it's actually the closest ancestor that is returned.The correct code would be:
I wouldn't recommend binding the event handler to alllllllll anchor tags; this will be inefficient if there's a number of those elements on the page. Instead I would strongly recommend using delegate() or live() instead.
This will bind the event handler to the
table
(once), and then uses JavaScripts event bubbling mechanisms to detect the click on the elements which match the selector passed in the first argument (in this case your delete buttons).尝试
Try
查看工作演示
你不能在那里使用
closest
,试试这个:
parent()
用于返回到链接的父级td
,然后prev()
用于查找的上一个同级>td
最后使用find
方法搜索input
。更多信息:
See Working Demo
You can't use
closest
there, try this:The
parent()
is used to go back to parenttd
of the link and thenprev()
is used to find the previous sibling oftd
and finally withfind
method,input
is searched for.More Info: