2017-03-18 39 views
1

我嘗試選擇所有筆劃屬性併爲每個對應的元素返回它們的值。只有,我使用each(),map()我無法做到。jquery選擇值屬性並應用每個值

我有一個函數

function (el, i) { 
    i = $('.line-code path').attr('stroke'); 
    return i 
} 

有了這一個,我只選擇第一種顏色適用於所有元素,這是不是我想要的。

這裏是我要選擇的元素(總共有33,但我只放3)

<path d="M720.5 521.5H785" stroke="#4990E2"/> 
<path d="M757.5 541.5H787" stroke="#000"/> 
<path d="M808.5 541.5H911" stroke="#FFF"/> 

,然後用我的功能,我想申請檢索到每個相應的顏色元件。

PS:在我的腳本中較高,我將所有顏色定義爲「無」,由於此功能,我想重新應用原始顏色。

非常感謝!

+0

什麼_are_那些相應的元素?你能提供一些樣品嗎? – Psi

回答

1

您可以使用array#map來獲取所有值。

var arr=[]; 
 
//iterating the path 
 
$('path').map(function(v){ 
 
//push values of stroke into the array 
 
arr.push($(this).attr('stroke')); 
 
}); 
 
$('p').map(function(i,v){ 
 
//for each p assign a color from the array 
 
$(this).css("color",arr[i]) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<path d="M720.5 521.5H785" stroke="#4990E2"/> 
 
<path d="M757.5 541.5H787" stroke="#000"/> 
 
<path d="M808.5 541.5H911" stroke="#eee"/> 
 
<p>element 1</p> 
 
<p>element 2</p> 
 
<p>element 3</p>

1

這裏有一個.map()普通的JavaScript。詳細摘錄評論:

代碼片段

// Collect all <path>s in a NodeList 
 
var paths = document.querySelectorAll('path'); 
 

 
/* Use map() method to convert NodeList 
 
|| into an array and to use getAttribute() 
 
|| method on each of the <path>'s stroke 
 
|| and finally return an array of stroke 
 
|| values (ie colors) 
 
*/ 
 
var colors = Array.prototype.map.call(paths, function(obj) { 
 
    var shade = obj.getAttribute('stroke'); 
 
    return shade; 
 
}); 
 

 
console.log(colors);
<svg height="400" width="400"> 
 
<path d="M 5.5 21.5 l 85 200" stroke="#4990E2" stroke-width='5'/> 
 
<path d="M 7.5 21.5 l 187 170" stroke="#000" stroke-width='15'/> 
 
<path d="M 8.5 41.5 l 300 10" stroke="#F00" stroke-width='5'/> 
 
</svg>