【问题标题】:Using two variables as selectors to call a function (jQuery)使用两个变量作为选择器来调用函数(jQuery)
【发布时间】:2019-03-07 18:16:36
【问题描述】:

有没有可能在声明了两个var之后,一起使用它们来调用jQuery中的一个函数?

喜欢:

var test1 = $('#mytest1');
var test2 = $('#mytest2');

test1,test1.fadeOut(100);

【问题讨论】:

  • 我建议你使用 JSLint 来帮助你找到脚本中的常见错误,如果你尝试做类似var1, var2.method() 的事情,它会说Expected an assignment or function call and instead saw an expression

标签: javascript jquery var


【解决方案1】:

是的。您可以将选择器包含在 $ 函数的引号中:

$('#mytest1, #mytest2').fadeOut(2000);
#mytest1, #mytest2 {
  width: 50px;
  height: 50px;
  margin: 5px;
  background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mytest1"></div>
<div id="mytest2"></div>

如果您希望使用已声明的现有变量,可以使用.add(),如this answer 中所述:

var test1 = $('#mytest1');
var test2 = $('#mytest2');

$(test1).add(test2).fadeOut(2000);
#mytest1, #mytest2 {
  width: 50px;
  height: 50px;
  margin: 5px;
  background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mytest1"></div>
<div id="mytest2"></div>

【讨论】:

  • 您应该“通常隐藏”第一个 sn-p 并显示第二个...;) +1
【解决方案2】:

如果您还没有两个变量,只需选择两个变量。参考。 http://learn.jquery.com/using-jquery-core/selecting-elements/#selecting-elements-with-a-comma-separated-list-of-selectors

$('#mytest1, #mytest2').fadeOut();

如果您已经在两个单独的变量中同时拥有这两个变量,则可以将它们组合起来。参考。 http://api.jquery.com/add/

test1.add(test2).fadeOut();

【讨论】:

  • 哎呀...你居然回复得跟我一样快!我没有看到。 ;)
  • 这也许就是我想要的 :) 谢谢
猜你喜欢
  • 2016-05-26
  • 1970-01-01
  • 2013-06-10
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
相关资源
最近更新 更多