【问题标题】:Pass multiple jQuery element selectors to a function将多个 jQuery 元素选择器传递给一个函数
【发布时间】:2012-09-09 21:45:46
【问题描述】:

myFunc() 绑定到文档滚动,因此会被大量调用。我想将 HTML 选择存储在 var 中并将它们传递给函数。当我在下面运行我的示例时,我收到控制台错误Unable to get value of the property 'css': object is null or undefined

var a1 = $('#a1');
var a2 = $('#a2');

$(document).bind("scroll", function() {
  setTimeout(myFunc, 1000, a1, a2);
}

function myFunc(a1, a2) {
  a1.css('color', 'blue');
  a2.css('font-weight', 'bold');
}

如何将存储在变量中的多个 jQuery 选择器传递给函数?

【问题讨论】:

    标签: javascript jquery function jquery-selectors


    【解决方案1】:
    $(document).bind("scroll", function() {
      setTimeout(function() {
          myFunc(a1, a2);
        },1000);
    }); // close );
    
    function myFunc(a1, a2) {
      a1.css('color', 'blue');
      a2.css('font-weight', 'bold');
    }
    

    【讨论】:

    • OP 的代码不应该做同样的事情吗(旧浏览器除外)?
    【解决方案2】:

    尝试以下方法:

    $(document).bind("scroll", function() {
        setTimeout(function() {
            myFunc(a1, a2);
        }, 1000);
    }); // and close properly your function
    

    【讨论】:

      【解决方案3】:

      您的a1a2 变量可以在页面上存在#a1#a2 的元素之前设置(特别是如果它没有包含在onload/ready 处理程序中并且脚本位于标题)。我会这样设置,以确保 #a1#a2 在滚动事件发生时存在。

      var a1 = undefined;
      var a2 = undefined;
      
      $(document).bind("scroll", function() {
        if(typeof(a1) === "undefined") { a1 = $("#a1");} //will only reset a1 if undefined
        if(typeof(a2) === "undefined") {a2 = $("#a2");}
      
        setTimeout(function(){myFunc(a1,a2)}, 1000);
      }); //don't forget your ')'
      
      function myFunc(a1, a2) { 
        a1.css('color', 'blue');
        a2.css('font-weight', 'bold');
      }
      

      【讨论】:

        【解决方案4】:

        您还可以将元素存储在数组中:

        jsBin demo

        var a1 = ['#a1','#a2'];
        
        $(document).bind("scroll", function() {
            setTimeout(function() {
                myFunc(a1);
            }, 1000);
        });
        
        function myFunc(el) {
          $(el[0]).css('color', 'blue');
          $(el[1]).css('font-weight', 'bold');
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-13
          • 2012-08-12
          • 2011-07-15
          • 2020-11-24
          • 1970-01-01
          • 2019-01-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多