繁体   English   中英

如何使用jQuery和Waypoint获取$ this的ID

[英]How do I grab the ID of $this using jQuery and Waypoints

我试图获取航点元素的ID,然后在滚动到达该航点时将该ID值作为类添加到正文中。 不过,这似乎不起作用。

的HTML

<body class="bg-1">
<div id="content">
    <div class="cover">
        <h2>Title</h2>
        <p class="keep-scrolling">Keep scrolling along</p>
    </div>
    <section class="stats">
        <article id="bg-1">
            /* stuff */
        </article>
        <article id="bg-2">
            /* stuff */
        </article>
        <article id="bg-3">
            /* stuff */
        </article>
        <article id="bg-4">
            /* stuff */
        </article>
    </section>
</div>
</body>

Java脚本

$(function() {
  $("article").waypoint(function(direction) {  //callback when waypoint is reached, with direction of scroll as a parameter
    var $this = $(this); // caching the waypoint element

    if($this.attr("id") == "bg-1") {
      $("body").removeClass();
      $("body").addClass('bg-1');
    } else if($this.attr("id") == "bg-2") {
      $("body").removeClass();
      $("body").addClass("bg-2");
    } else if($this.attr("id") == "bg-3") {
      $("body").removeClass();
      $("body").addClass("bg-3");
    } else if($this.attr("id") == "bg-4") {
      $("body").removeClass();
      $("body").addClass("bg-4");
    } else {
      $("body").addClass("bg-1");
    };

  });
});

我有多种获取ID的方法,但无法正确获取语法。

您使用的Waypoint回调功能错误。

参照API,它应该为您工作:

$(function() {
  $("article").waypoint({
    handler: function(direction) {
      $("body").removeClass(function(index, css) {
        return (css.match(/(^|\s)bg-\S+/g) || []).join(' ');
      });
      //or $("body").removeClass();
      $("body").addClass(this.element.id);
    }
  });
});

我进一步调整了您的解决方案:

  • bg-开头删除正文中的所有类(请参阅答案以供参考)
  • id添加为类(删除了不必要的“ if”构造)

mapk,您$ this与jquery选择器的响应有关,在您的情况下,它检索article元素列表,并且您的算法将其威胁为一个。

考虑在代码内使用foreach

$(function() {
  $("article").waypoint(function(direction) {  //callback when waypoint is reached, with direction of scroll as a parameter
    $(this).each(function(i,val){
    var $this = $(val); // caching the waypoint element

    if($this.attr("id") == "bg-1") {
      $("body").removeClass();
      $("body").addClass('bg-1');
    } else if($this.attr("id") == "bg-2") {
      $("body").removeClass();
      $("body").addClass("bg-2");
    } else if($this.attr("id") == "bg-3") {
      $("body").removeClass();
      $("body").addClass("bg-3");
    } else if($this.attr("id") == "bg-4") {
      $("body").removeClass();
      $("body").addClass("bg-4");
    } else {
      $("body").addClass("bg-1");
    };


   });

  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM