问题
I am trying to make an array from elements with a certain class in my web page. The array should get the videofile attribute value from all a tags with the class videoLink.
The final values in the array should be.
cycling_large, ocean_medium, winecountry_part1
<a class="videoLink" videofile="cycling_large" ></a>
<a class="videoLink" videofile="ocean_medium" ></a>
<a class="videoLink" videofile="winecountry_part1" ></a>
I tried this but, does not work.
var values = $('.videoLink').map(function() { return this.attr('videofile'); }).get();
Thanks in advance.
回答1:
var links = document.getElementsByClassName("videoLink");
var values = [].map.call(links, function (el) {
return el.getAttribute("videofile");
});
Because you don't jQuery for simple things.
Browser support:
- ES5 shim
- DOM shim
回答2:
Change return this.attr('videofile');
to return $(this).attr('videofile');
.
You need to enclose the this
in $()
so it becomes a jQuery object that you can then call attr()
on.
Example: http://jsfiddle.net/r9xJn/
回答3:
var result = $.map($('a.videoLink'), function(a) {
return $(a).attr('videofile');
});
Working example: http://jsfiddle.net/hY6zM/
来源:https://stackoverflow.com/questions/7988719/javascript-array-from-all-elements-with-a-certain-class-name