繁体   English   中英

如何为每篇文章应用jquery函数

[英]How to apply jquery function for each article

我有一个像这样的 DOM。 我有一个 jquery 函数,用于检查文章中是否有“可见”类,将其删除并将其添加到单击的“热点”类中。 此功能必须独立于其他“文章”对每个“文章”起作用。 我创建了这个函数,但它不起作用:

 $("article").each(function() { $("article .hotspot").on("touchstart", function() { $(".hotspot.visible").not(this).removeClass('visible'); $(this).toggleClass('visible'); }) })
 <article> <div class="hotspot"> <div class="hotspot"> </article> <article> <div class="hotspot"> <div class="hotspot"> </article>

你有什么建议吗?

如果删除.each()循环,主要问题将得到解决,请查看下面的说明。

解释:

由于您使用.each()方法进行循环,因此在每次迭代中都会附加事件,在您的情况下,您有两篇article's因此事件将附加到每个项目两次,然后在触发touchstart时触发touchstart

然后,因为您使用的是toggleClass() ,第一个事件将添加或删除该类,然后第二个事件将执行相反的操作,看起来该事件根本没有被触发。

 $("article .hotspot").on("touchstart click", function() { $(this).parent().find(".hotspot.visible").not(this).removeClass('visible'); $(this).toggleClass('visible'); });
 .visible { background-color: green; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <article> <div class="hotspot">1</div> <div class="hotspot">2</div> </article> <br> <article> <div class="hotspot">1</div> <div class="hotspot">2</div> </article>

注意:要检查我已经解释过的行为,您可以看到console.log('Event fired')console.log('Event fired')在单击时触发了两次。

 $("article").each(function() { $("article .hotspot").on("touchstart click", function() { $(".hotspot.visible").not(this).removeClass('visible'); $(this).toggleClass('visible'); console.log('Event fired'); }) })
 .visible { background-color: green; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <article> <div class="hotspot">1</div> <div class="hotspot">2</div> </article> <article> <div class="hotspot">1</div> <div class="hotspot">2</div> </article>

这应该适合你

$("article .hotspot").on("touchstart", function() {
    $("article .hotspot").removeClass('visible');
    $(this).addClass('visible');
});

或者

$("article .hotspot").on("click", function() {
    $("article .hotspot").removeClass('visible');
    $(this).addClass('visible');
});

干得好:

 $("article").each(function() { $(this).children('.hotspot').on("touchstart click", function(){ $(this).siblings().removeClass('active'); $(this).addClass('active'); }) })
 article .hotspot.active{ background: red; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <article> <div class="hotspot">1</div> <div class="hotspot">2</div> </article> <br> <article> <div class="hotspot">1</div> <div class="hotspot">2</div> </article>

如果您想选择多个活动热点,请删除:

$(this).siblings().removeClass('active');

并改变:

$(this).addClass('active');

为了

$(this).toggleClass('active');

暂无
暂无

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

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