简体   繁体   English

在同一个类的多个元素上运行一个jQuery函数

[英]Run one jQuery function on multiple elements with the same class

I have problem with running one jquery function on two or more elements. 我在两个或多个元素上运行一个jquery函数时遇到问题。 It runs properly on the first element in the HTML code, but doesn't work properly on others. 它可以在HTML代码中的第一个元素上正常运行,但不能在其他元素上正常运行。

I have this jQuery: 我有这个jQuery的:

$(window).load(function(){
$('.background_square_1 li.bg_square').hide();

function rotate() {
$(".background_square_1 li.bg_square").first().appendTo('.background_square_1').fadeOut(500);
$(".background_square_1 li.bg_square").first().fadeIn(500);

setTimeout(rotate, 10000);
}
rotate();
});

And HTML like this: 像这样的HTML:

<ul class="background_square_1 gallery_background">
<li class="bg_square bg_1"></li>
<li class="bg_square bg_2"></li>
<li class="bg_square bg_3"></li>
<li class="bg_square bg_4"></li>
</ul>

<ul class="background_square_1 gallery_background">
<li class="bg_square bg_1"></li>
<li class="bg_square bg_2"></li>
<li class="bg_square bg_3"></li>
<li class="bg_square bg_4"></li>
</ul>

Basically, what I am trying to achiveve is to run the function on both (but can be more!) ul elements with background_square_1 class. 基本上,我要达到的目的是在两个(但可以更多!)具有background_square_1类的ul元素上运行该函数。

Truth be told, I do not work with javascript or jQuery, so please keep this in mind. 说实话,我不使用javascript或jQuery,因此请记住这一点。

Here is Fiddle showing my problem: http://fiddle.jshell.net/bWHPg/ 这是Fiddle显示我的问题: http : //fiddle.jshell.net/bWHPg/

Just target that class directly. 只需直接针对该课程。 So for example 所以举个例子

$(".gallery_background").function()

Or, if the function can't be called like that and you want to process each element with something else you could do 或者,如果函数不能那样调用,而您想用其他方法处理每个元素,则可以执行

$(".gallery_background").each(function(index, item){
    var elm = $(this);
    ... Do stuff ...
})

I could have got index and item the wrong way round but you get the idea :) 我本可以以错误的方式获取索引和项目,但您知道了:)

Wrap your code inside document.ready rather than window.load 将您的代码包装在document.ready而不是window.load中

$(function() {
   //jQuery code here
});

just remove .first() in your code your code would work fine 只要在您的代码中删除.first(),您的代码就可以正常工作

working fiddle here: http://fiddle.jshell.net/bWHPg/2/ 在这里工作的小提琴: http : //fiddle.jshell.net/bWHPg/2/

http://fiddle.jshell.net/bWHPg/5/ http://fiddle.jshell.net/bWHPg/5/

setInterval(function() { 
  $('.background_square_1').find('li:first')
        .fadeOut(500)
        .next()
        .fadeIn(500)
         .next()
        .fadeIn(500)
        .end()
        .appendTo(".background_square_1");
},  500);

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

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