选择特定的最接近元素 [英] Select specific closest element

查看:78
本文介绍了选择特定的最接近元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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>

当我单击锚标记时,我想选择最靠近我的链接的<input>,并获取其值.我怎样才能做到这一点 ?我在尝试:

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);
  });

但没有任何运气.

推荐答案

closest函数的名称极具误导性:实际上是返回的最接近的祖先.

The name of the closest function is extremely misleading: it's actually the closest ancestor that is returned.

正确的代码是:

var value = $(this).parent().siblings('td').children('input').val();

我不建议将事件处理程序绑定到alllllllll锚标记.如果页面上有许多这样的元素,这将是低效的.相反,我会强烈建议使用 delegate()

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.

$('#objects').delegate('a.delete', 'click', function (e) {
    e.preventDefault();
    var val = $(this).parent('td').siblings('td').find('input').attr('value');
    alert(val);
});

这会将事件处理程序绑定到table(一次),然后使用JavaScript事件冒泡机制来检测对与第一个参数(在本例中为删除按钮)中传递的选择器匹配的元素的单击.

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).

这篇关于选择特定的最接近元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆