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

时间:2016-10-06 16:52:17

标签: javascript jquery jquery-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>

的Javascript

$(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,但无法正确使用语法。

2 个答案:

答案 0 :(得分:2)

你使用的是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-开始删除正文中的所有课程(请参阅this答案以供参考)
  • id添加为类(删除不必要的'if'结构)

<强> Example

答案 1 :(得分:0)

mapk,你这与你的jquery选择器的响应有关,在你的情况下,它检索一个文章元素列表,你的算法将它作为一个单一的威胁。

考虑在代码中使用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");
    };


   });

  });
});