将点击事件处理程序仅添加到某些子级 [英] Add click event handler to only some children

查看:56
本文介绍了将点击事件处理程序仅添加到某些子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表格中有几行采用以下格式,

I have a few rows in my table in the following format,

<tr class = "parent">
    <td class = "first"> asdf </td>
    <td class> qwerty </td>
    <td class> zxcv </td>
    <td class> 1234 </td>
</tr>

我想在单击"asdf"时执行操作A,在单击该行的其余子级中的任何一个时执行操作B.我写了,

I want to perform action A when I click on "asdf" and action B when any one of the remaining children of the row is clicked. I wrote,

//Action A
$('.first').live('click', function() { console.log('first clicked'); });

//Action B
$('.parent').children().not('.first').live('click', function() { console.log('others clicked'); });

由于某种原因,操作B的代码无法正常工作.由于可以添加/删除行,因此这两个操作都需要实时"附件.

For some reason the code for Action B is not working. I need the "live" attachment for both actions since rows can be added/deleted.

我该怎么办?

推荐答案

<table>
  <tr class="parent">
    <td class="first"> asdf </td>
    <td class> qwerty </td>
    <td class> zxcv </td>
    <td class> 1234 </td>
  </tr>
</table>

$('tr.parent').find('td').live('click', function(){
    if ($(this).is('.first')) {
        console.log('Has .first.');
    } else {
        console.log('Does not have .first.');
    }
});

http://jsfiddle.net/GnX4L/

也许是更好的方法:

$('tr.parent').find('td').live('click', function(){
    if ($(this).is(':first-child')) {
        console.log('Is first child.');
    } else {
        console.log('Not first child.');
    }
});

http://jsfiddle.net/GnX4L/1/

这篇关于将点击事件处理程序仅添加到某些子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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