jQuery悬停事件未启动

jQuery hover event not firing

本文关键字:启动 事件 悬停 jQuery      更新时间:2023-09-26

下面给出的代码示例:

(function (window, document) {
$('.rating_title_container').parents('.item_row_def').hover(function() {
          setTimeout(function() {
              system.console('Worked');
          }, 1000);
        });
 })(window, document);  

我对JS,jQuery还是个新手。有人能解释一下我在这里缺了什么吗?已在中发布代码http://jsfiddle.net/p7gBy/5/

HTML

  <table>
    <thead>
      <tr>
        <th class="item_row_def" onclick="sort(3);">
          <table class="col-header">
            <tbody>
              <tr>
                <td>
                  <h2 class="header_title rating_title_container">Rating</h2>
                </td>
              </tr>
            </tbody>
          </table>
        </th>
      </tr>
    </thead>
  </table>

您需要将事件处理程序绑定到这样一个文档中(用这个替换上面的代码,请参阅):

$(document).ready(function(){
    $('.rating_title_container').parents('.item_row_def').hover(function() {
      setTimeout(function() {
          system.console('Worked');
      }, 1000);
    });
});

试试这个代码:

(function (window, document) {
$('.rating_title_container').parents('.item_row_def').hover(function() {
          setTimeout(function() {
              alert('Worked');
          }, 1000);
        });
})(window, document); 

检查小提琴http://jsfiddle.net/AXepU/

尝试以下假设在文档准备好时调用代码:

jQuery(function (window, document) {
$('.rating_title_container').parents('.item_row_def').hover(function() {
      setTimeout(function() {
          system.console('Worked');
      }, 1000);
    });
});

同时,您在末尾超过了});,这会引发错误

您必须包含函数doc ready,然后一切都会正常工作:

$(function(){ // <----------------------------try enclosing within this from here
   (function (window, document) {
      $('.rating_title_container').parents('.item_row_def').hover(function() {
        setTimeout(function() {
            alert('Worked');
        }, 1000);
      });
   })(window, document); 
}); //<---------------------------------------- to here.

大多数事件应该写在document ready处理程序中。

这个:

$(document).ready(function() {
   // Handler for .ready() called. 
});

这个:

$(function() {
    // Handler for .ready() called.
});

相同。第二个只是doc ready处理程序的较短版本。

阅读有关.ready()处理程序的更多信息