jquery选择值属性并应用每个值

时间:2017-03-18 13:25:26

标签: javascript jquery

我尝试选择所有笔划属性并为每个对应元素返回它们的值。只是,我使用了每个(),map()我不能这样做。

我有一个功能

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:在我的剧本中,我将所有颜色定义为&#34;无&#34;,由于此功能,我想重新应用原始颜色。

非常感谢!

2 个答案:

答案 0 :(得分:1)

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

&#13;
&#13;
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])
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是一个$query = "SELECT name, date, host, info FROM `conferences`"; 纯JavaScript。详情请参阅代码段:

<强>段

&#13;
&#13;
.map()
&#13;
// 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);
&#13;
&#13;
&#13;