必须在事件触发前写入警报

时间:2014-04-14 17:55:17

标签: javascript jquery

当用户点击名为winners的表时,我遇到了jquery片段的问题。代码

 $('#winners tr').click(function() {
      alert(223);
    });

只有在我在此代码段之前发出提醒时才会触发:

  alert(1);
  $('#winners tr').click(function() {
    alert(223);
   });

整个代码如下所示。问题是底部的代码片段。

 <script type="text/javascript" src="http://www.google.com/jsapi"></script>
  <script type="text/javascript">
  google.load("jquery", "1.7.1");

  function listen(last_modified, etag) {
       $.ajax({
           'beforeSend': function(xhr) {
               xhr.setRequestHeader("If-None-Match", etag);
               xhr.setRequestHeader("If-Modified-Since", last_modified);
           },
           url: '/test/sub',
           dataType: 'text',
           type: 'get',
           cache: 'false',
           success: function(data, textStatus, xhr) {
                     /*REMOVED CODE*/
               });

               /* Start the next long poll. */
               listen(last_modified, etag);
           },
           error: function(xhr, textStatus, errorThrown)
           {
             //$('#data').prepend(textStatus + ' | ' + errorThrown);
           }
       }); 
   }; 

   google.setOnLoadCallback(function() {
       /* Start the first long poll. */
       /* setTimeout is required to let the browser know
          the page is finished loading. */
       setTimeout(function() {
           listen('Thu, 1 Jan 1970 00:00:00 GMT', '0');
       }, 500);
   });
    //alert(1);
    $('#winners tr').click(function() {
      alert(223);
    });
  </script>

感谢您的帮助!

2 个答案:

答案 0 :(得分:6)

问题是你的代码是在元素出现在DOM之前执行的,所以$('#winners tr')为空,除非你有这个警告阻止脚本。

通常的解决方案是将整个script元素放在body元素的末尾而不是head内。或者您可以将代码包装在jquery ready事件处理程序中。

当您使用谷歌加载时,最好的方法是将点击绑定代码移动到您传递给google.setOnLoadCallback的回调中。

答案 1 :(得分:1)

如果您的代码位于页面的头部,则将其放在文档就绪处理程序中 -

$(document).ready(function() {
  function listen(last_modified, etag) {
       $.ajax({
           'beforeSend': function(xhr) {
               xhr.setRequestHeader("If-None-Match", etag);
               xhr.setRequestHeader("If-Modified-Since", last_modified);
           },
           url: '/test/sub',
           dataType: 'text',
           type: 'get',
           cache: 'false',
           success: function(data, textStatus, xhr) {
                     /*REMOVED CODE*/
               });

               /* Start the next long poll. */
               listen(last_modified, etag);
           },
           error: function(xhr, textStatus, errorThrown)
           {
             //$('#data').prepend(textStatus + ' | ' + errorThrown);
           }
       }); 
   }; 

   google.setOnLoadCallback(function() {
       /* Start the first long poll. */
       /* setTimeout is required to let the browser know
          the page is finished loading. */
       setTimeout(function() {
           listen('Thu, 1 Jan 1970 00:00:00 GMT', '0');
       }, 500);
   });
    //alert(1);
    $('#winners tr').click(function() {
      alert(223);
    });
});
相关问题