【问题标题】:jQuery append only if the div hasn't previously been appended?jQuery 仅在 div 之前未附加的情况下附加?
【发布时间】:2019-01-29 08:07:13
【问题描述】:

我正在开发一个滚动文本 jQuery,它应该滚动几个名为 .vs-container 的 div 的文本。我在幻灯片中使用它们,这就是为什么在 codepen 中多次创建具有相同 ID 的 div(这就是我网站上的方式)。 但问题是相同的 div 会一次又一次地附加。

是否可以仅在 div 不存在的情况下追加它?

 function scrollText() {
   setInterval(function() {
           scrollAppend($(".vs-container"));
       }, 1500);
 };

 function scrollAppend(obj) {
    var $self = $(".vs-container");
    var lineHeight = $self.find(".vs-content:first-child").height();

    $(".vs-content:first-child").addClass("active");

     $self.animate({
         "marginTop": -lineHeight + "px"
     }, 300, function() {
         $self.css({
             marginTop: 0
         }).find(".active:first-child").appendTo($self);
     })
}

scrollText();

https://codepen.io/jockebq/pen/PVzpWR

【问题讨论】:

  • divs with the same ID´s are created multiple times 是无效的 HTML - 最好先解决这个问题。
  • 但它们显示在不同的幻灯片上,我只是将它们放在那里以显示问题。我希望滚动文本在幻灯片之间继续。

标签: jquery


【解决方案1】:

您可以使用 if(!$('.test').length) 来检查 DOM 元素是否不存在 {// 在此处执行操作 }

【讨论】:

  • 但是如果事先不知道 div 的 ID,这可能吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
  • 1970-01-01
  • 2015-10-13
  • 2020-08-04
  • 2022-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多