简体   繁体   English

jQuery addClass与具有Waypoint的相同类名的元素

[英]jQuery addClass to element with same class name with Waypoints

I have an event in which I need to add a class to an element with a matching class name. 我有一个事件,需要在其中将一个类添加到具有匹配类名称的元素中。 For example: 例如:

<a class="one"></div>
<a class="two"></div>

<div class="one"></div>
<div class="two"></div>

How do I find and add an additional class to the element with the matching class name? 如何找到具有匹配类名称的元素并将其添加到元素中? Here is my script, I need it to target the tag with matching class. 这是我的脚本,我需要它以匹配类的标记为目标。

jQuery('div.two').waypoint(function(direction) {
  if (direction === 'down') {
    jQuery(this).addClass("active") // to <a> element that shares same class
  }
  else {
  }
});

I'm not familiar with this plugin but I'll give it a shot. 我对这个插件不熟悉,但我会试一试。 Based off what you've provided I think your problem is: 根据您提供的信息,我认为您的问题是:

jQuery(this).addClass("active")

Since you already know the class, just do: 由于您已经了解该课程,因此请执行以下操作:

var tempClass = $(this).attr("class");
jQuery("a."+tempClass).addClass("active");

Just select by class names. 只需按类别名称进行选择即可。

Array.prototype.forEach.call(document.querySelectorAll(".one"), function(el) {
    el.classList.add("whateverClass");
});

Instead of a for loop, this uses the prototype method forEach with the call method to turn the NodeList into an array list, adding the class to each element with the class "one" 代替for循环,它使用原型方法forEachcall方法将NodeList转换为数组列表,将类添加到具有“ one”类的每个元素中

DEMO 演示

You probably want to remove the class from the others first, then add to the applicable <a> 您可能想先从其他类中删除该类,然后将其添加到适用的<a>

jQuery('div.two').waypoint(function(direction) {
  if (direction === 'down') {
     /* remove prior active class */
     jQuery("a.active").removeClass('active');
     /* add to current one */
     jQuery("a.two").addClass('active');
  }
  else {
  }
});

To make this more generic I would add a class like waypoint to all the content elements as well as a data-point to be able to simplify instances. 为了使它更通用,我将向所有内容元素添加一个类,如waypoint以及一个能够简化实例的data-point

<div data-point="one" class="waypoint"></div>

JS JS

jQuery('.waypoint').waypoint(function(direction) {
  if (direction === 'down') {
     /* remove prior active class */
     jQuery("a.active").removeClass('active');
     /* add to current one */
      var linkClass=$(this).data('point')
     jQuery("a." + linkClass).addClass('active');
  }
  else {
  }
});

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

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