通过jquery为多个div设置css?
您好,我想为多个div应用通过jquery为多个div设置css?,jquery,css,Jquery,Css,您好,我想为多个div应用%中的cssleft属性。我试过下面的代码 HTML <div class="inner-nav blue" rel="blue"> <a href="#" style="display: block; left: 0%;"> Text1 <br> </a> </div> <div class="inner-nav blue" rel="blue"> <
%
中的cssleft
属性。我试过下面的代码
HTML
<div class="inner-nav blue" rel="blue">
<a href="#" style="display: block; left: 0%;">
Text1 <br>
</a>
</div>
<div class="inner-nav blue" rel="blue">
<a href="#" style="display: block; left: 0%;">
Text2 <br>
</a>
</div>
<div class="inner-nav blue" rel="blue">
<a href="#" style="display: block; left: 0%;">
Text3 <br>
</a>
</div>
<div class="inner-nav blue" rel="blue">
<a href="#" style="display: block; left: 0%;">
Text4 <br>
</a>
</div>
代码的问题在于,您在错误的位置定义了
索引。您将获得调用css()
的元素的索引,但它将始终是集合中的第一个,因此索引将始终为0:
$(".inner-nav").each(function (index) {
$(this).find("a:first").css("left", function () {
var f = index * 25;
f = f + "%";
return f;
});
});
不需要each()
循环。许多jQuery方法,包括css()
单独处理与选择器匹配的每个元素的循环:
$(".inner-nav").find("a:first").css("left", function( index ) {
var f= index*25;
f=f+"%";
return f;
});
我认为您的问题是锚定的索引,它总是0
,因此0%
应用于每个锚定,因此您可以尝试以下方法:
$(".inner-nav").each(function () {
var idx = $(this).index(); // get the div's index
$(this).find("a:first").css("left", function (index) {
var f = idx * 25; // and use it here.
f = f + "%";
return f;
});
});
要简化此过程,您可以使用它:
$(".inner-nav").each(function (idx) {
$(this).find("a:first").css("left", idx * 25 + "%");
});
您尚未将索引作为函数属性传递。因此,它没有定义内部循环。这里的索引也基于0。所以第一个div的第一个锚点将剩下0%。试试这个:
$(".inner-nav").each(function(index){
$(this).find("a:first").css("left",index*25+'%');
});
试试这个
$(".inner-nav").each(function (i) {
var inn = $(this).index();
var f = parseInt(inn) * 25;
var cf = f + "%";
$(this).find("a:first").css("left", cf);
});
与OP有什么区别?感谢@oGeez对我的帮助,感谢我在自己的代码中使用的有关索引的知识。你能给我一个链接让我深入理解吗?如果你能解释我,那对我来说就像是一个聚会:)和
$(".inner-nav").each(function (i) {
var inn = $(this).index();
var f = parseInt(inn) * 25;
var cf = f + "%";
$(this).find("a:first").css("left", cf);
});