【问题标题】:Should I keep using document.ready Jquery我应该继续使用 document.ready Jquery
【发布时间】:2014-04-07 23:10:42
【问题描述】:

我有以下代码:

  $(document).ready(function(){
  $('td.rightImage, .leftImage a').click(function(){
   if($(this).attr( "id" )){
   _gaq.push(['_trackEvent', 'sidebanner', 'click', $(this).attr('id'),0,true]);
   }
 else{
 _gaq.push(['_trackEvent', 'sidebanner', 'click', $(this).attr('href'),0,true]);
 }
 });
 });

    $(document).ready(function(){
   $("a[href$='.pdf']").click(function(){
  _gaq.push(['_trackEvent', 'pdf', 'click',$(this).attr('href'),0,true]);
    });
    });
   $(document).ready(function(){
   $("a[href$='.zip']").click (function(){
   _gaq.push(['_trackEvent', 'zip', 'download',$(this).attr('href'),0,true]);
    });
    });

我是否应该继续为我想要的每个 onclick 事件准备好文档?如果不是,有什么更好的方法来编写上述代码?

谢谢

【问题讨论】:

  • 让它只是一个函数,毕竟它们都是同时调用的。
  • 是的!使用 jQuery 或其他框架或纯 JS 都没关系。请记住,当所有元素都已经在它们的位置时执行这种代码,在 jQuery 中意味着document.ready()。您的脚本会在可用时立即执行 - 甚至在加载 HTML 文档之前 - 这就是 document.readybody.onload 的含义!

标签: jquery onclick document


【解决方案1】:

有一种更好的方法 - 将它们全部放在一个 DOM 就绪事件中。

【讨论】:

    【解决方案2】:

    在 document.ready 上使用

    //OR
    //$(function(){
    $(document).ready(function () {
        $('td.rightImage, .leftImage a').click(function () {
            if ($(this).attr("id")) {
                _gaq.push(['_trackEvent', 'sidebanner', 'click', $(this).attr('id'), 0, true]);
            } else {
                _gaq.push(['_trackEvent', 'sidebanner', 'click', $(this).attr('href'), 0, true]);
            }
        });
        $("a[href$='.pdf']").click(function () {
            _gaq.push(['_trackEvent', 'pdf', 'click', $(this).attr('href'), 0, true]);
        });
        $("a[href$='.zip']").click(function () {
            _gaq.push(['_trackEvent', 'zip', 'download', $(this).attr('href'), 0, true]);
        });
    });
    

    【讨论】:

      【解决方案3】:

      你可以合并它们,$(document).ready 可以这样写。

      $(function(){
         // DOM Ready - do your stuff 
      });
      

      【讨论】:

        猜你喜欢
        • 2012-01-23
        • 1970-01-01
        • 1970-01-01
        • 2012-10-15
        • 1970-01-01
        • 2010-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多