jQuery悬停事件没有触发

时间:2013-02-19 04:29:38

标签: javascript jquery closures

下面给出的代码示例:

(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>

4 个答案:

答案 0 :(得分:0)

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

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

同时你最后超过});,这会引发错误

答案 1 :(得分:0)

你需要在像这样的doc中绑定你的事件处理程序(用这个代替上面的代码并看看):

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

答案 2 :(得分:0)

试试这段代码:

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

})(window, document); 

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

答案 3 :(得分:0)

你必须附上该函数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处理程序的缩短版本。

Read More about .ready()处理程序

相关问题