2013-04-10 31 views
0

这是我的标记表格单元格:事件绑定到使用jQuery

<div id="divContainer"> 
    <div> 
     <table></table> 
    </div> 
    <div> 
     <table></table> 
    </div> 
    .... 
</div> 

我需要在所有td S中所有表(即分别存在div内)的注册mouseenter事件。

$(document).ready(function() { 
    $allTds = $('#divContainer').find("tr").find("td"); 
    ... 
    SomeFunction(); 
}); 

function SomeFunction(){ 
    $allTds.on({ 
     mouseenter: function (e) { 
      alert('hover'); 
     } 
    }); 
} 

但我没有收到任何警报。

+2

那么我没有看到你的标记示例中有任何'​​'..你确定它们存在吗? – 2013-04-10 06:18:17

+0

@Explosion Pills,它们是动态添加的。在萤火虫中,我看到了'td'的集合。 – mike44 2013-04-10 06:19:23

回答

1

您的事件处理程序不被束缚的原因是,当你进入文件准备好处理程序不存在<td>元素。

您应该为此使用事件委托。例如

window.jQuery(function($) { 
    $('#divContainer').on({ 
     mouseenter: function(e) { 
      alert('hover'); 
     } 
    }, 'td'); 
}); 

通过这种方式,它是#divContainer元素侦听事件,并作用于他们,如果他们从<td>起源。

http://api.jquery.com/on/#direct-and-delegated-events

也有在$allTds变量仅在文档准备好处理程序确定的,并不是在SomeFunction功能的范围范围界定问题。

3

他们应用事件监听器的方式很奇怪。

$('#divContainer').on('mouseenter','td',function() { 
    alert('mouse entered'); 
}); 

另外:缓存td元素很好,但为什么不坚持更简单的东西呢?

$allTd = $('#divContainer td'); 
+0

感谢您的回答。 – mike44 2013-04-10 06:37:23