2015-04-02 33 views
1
<div class="item" rel="a">1</div> 
<div class="item" rel="b">2</div> 

<div class="receive" rel="a">1</div> 
<div class="receive" rel="b">2</div> 

.item[rel='a'] { 
    width:50px; 
    height:50px; 
    background: pink; 
} 
.item[rel='b'] { 
    width:50px; 
    height:50px; 
    background: orange; 
    margin-left:20px; 
} 
.receive { 
    margin-top:20px; 
    border:1px solid; 
    width:50px; 
    height:50px; 
} 

如何讓接收器接收項目的顏色?我可以做匹配循環內的多個項目和屬性

bg = $('.item').css('background'); 
$('.receive').css('background',bg); 

但我希望它能匹配使用'rel'屬性,我有多個接收器。我應該循環嗎?

+0

你有多少條記錄..? – Yash 2015-04-02 10:26:12

+1

爲什麼不使用簡單的CSS呢? – haim770 2015-04-02 10:26:43

回答

2

做到在每個循環。

$('.item').each(function(idx) { 
    var rel = $(this).attr('rel'); 
    var bg = $(this).css('background'); 
    $('.recieve[rel="' + rel + '"]').css('background', bg); 
}); 

我想這就是你想要的。

您可以循環使用.item.recieve,在一天結束時無所謂。
這裏是一個小提琴,以表明它的工作原理:http://jsfiddle.net/Lg6yw7bj/1/

0

.css()在jquery中的方法接受回調函數,所以你可以使用它。

你可以試試這個:

$('.recieve').addClass('item'); // just add the class to make it work. 
 

 
/*$('.recieve').css('background', function(i){ 
 
    return $('.item').eq(i).css('background'); 
 
});*/
.item[rel='a'] { 
 
    width: 50px; 
 
    height: 50px; 
 
    background: pink; 
 
} 
 
.item[rel='b'] { 
 
    width: 50px; 
 
    height: 50px; 
 
    background: orange; 
 
    margin-left: 20px; 
 
} 
 
.recieve { 
 
    margin-top: 20px; 
 
    border: 1px solid; 
 
    width: 50px; 
 
    height: 50px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="item" rel="a">1</div> 
 
<div class="item" rel="b">2</div> 
 

 
<div class="recieve" rel="a">1</div> 
 
<div class="recieve" rel="b">2</div>

+0

哇我永遠不知道這是什麼,我btw? – 2015-04-02 12:19:47

+0

'i'表示循環中元素的索引。 @JamesLemon – Jai 2015-04-02 12:29:07

+0

爲什麼需要eq()? – 2015-04-02 12:29:43