不能组合两个选择器

Can't combine 2 selectors

本文关键字:两个 选择器 组合 不能      更新时间:2023-09-26

我有一个脚本,通过暂停淡出图片,然后再将其淡入。我想在脚本中添加更多的元素,这样它们就会同时淡出(如果我有单独的脚本,它们就不会同时淡出)。

var fadeinBox = $("#box2, #icons1");
var fadeoutBox = $("#box1, #icons2");
function fade() {
    fadeinBox.stop(true, true).fadeIn(2000);
    fadeoutBox.stop(true, true).fadeOut(2000, function() {
        var temp = fadeinBox;
        fadeinBox = fadeoutBox;
        fadeoutBox = temp;
        setTimeout(fade, 2000);
    });
}
fade();

如果我只使用一个选择器,脚本工作得很好。var fadeinBox = $("**#box2**")。但是,如果我有很多,它们就不起作用了。

你很接近了。我们将在这里使用承诺来确保函数以正确的顺序运行。

我们从fadeIn()返回.promise(),将.done()调用添加到我们执行fadeOut()的内部并返回.promise()。通过返回另一个promise,我们可以在链上附加第二个.done()来翻转指针并设置超时。

var $fadeIn = $("#box2, #icons1");
var $fadeOut = $("#box1, #icons2");
function fade() {
  $fadeIn
    .fadeIn(2000)
    .promise()
    .done(function () {
      return $fadeOut
        .fadeOut(2000)
        .promise();
    })
    .done(function() {
      var $temp = $fadeIn;
      $fadeIn = $fadeOut;
      $fadeOut = $temp;
      setTimeout(fade, 2000);
    });
}
fade();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box1">Box 1</div>
<div id="box2">Box 2</div>
<div id="icons1">Icons 1</div>
<div id="icons2">Icons 2</div>

引用:

  • https://api.jquery.com/promise/

(假设我理解正确)我相信你在这里遇到的问题是:

  1. 你正在收集页面上的物品,例如:var fadeinBox = $("#box2, #icons1");
  2. 新内容被添加到DOM
  3. 渐变函数正在被调用,但是"new"元素没有被"fade()'ed"

问题是,当你调用jQuery()时,它只收集它在查询被调用时可以看到的元素。

对于你的代码工作,你可能需要移动你的选择器到你的函数调用,所以它重新查询元素每次调用,例如:

function fade() {
    var fadeinBox = $("#box2, #icons1");
    var fadeoutBox = $("#box1, #icons2");
    fadeinBox.stop(true, true).fadeIn(2000);
    fadeoutBox.stop(true, true).fadeOut(2000, function() {
        var temp = fadeinBox;
        fadeinBox = fadeoutBox;
        fadeoutBox = temp;
        setTimeout(fade, 2000);
    });
}

如果可以的话,可以考虑使用类而不是id,如果它对你的应用程序有意义的话。尽管大多数浏览器都允许多个元素使用重复的id标签,但这不是一个好的做法。