检查列表中是否有任何元素具有事件

Check whether any element in a list has an event

本文关键字:元素 事件 任何 检查 是否 列表      更新时间:2023-09-26

是否可以循环遍历表单元格列表并检查是否有特定事件(例如click),然后执行回调函数?

您可以使用td选择器和each方法来循环并使用事件数据来获取您正在寻找的事件:

$("td").each(function () 
  {
    //Do you work here
  });
因此,对于下面的HTML:
<table id="t1">
    <tr>  <td id="t1A">A     <td> </tr>
    <tr> <td>B  <td> </tr>
    <tr> <td>C  <td> </tr>
    <tr> <td>D <td></tr>
</table>
<table id="t2">
    <tr>  <td id="t2A">A     <td> </tr>
    <tr> <td>B  <td> </tr>
    <tr> <td>C  <td> </tr>
    <tr> <td>D <td></tr>
</table>

您可以使用以下命令:

$("#t1A").click(function () {
    alert("t1A click event");
});
$("td").each(function () {
    var events = $._data(this, "events")
    if (!events) return;
    var clickEvents = events.click;
    if (!clickEvents) return;    
    if (clickEvents.length > 0) {
        alert($(this).attr("id") + " has a click event");
        $(this).click();   // Execute the click if you so desire.
    }
});

查看此示例:http://jsfiddle.net/sdnr6/1/