admin管理员组

文章数量:1325408

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.

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.

Share Improve this question edited Nov 2, 2011 at 23:44 Blender 299k55 gold badges458 silver badges510 bronze badges asked Nov 2, 2011 at 23:42 user973671user973671 1,6506 gold badges28 silver badges39 bronze badges 1
  • 1 videofile? I think you mean data-videofile... :P – Šime Vidas Commented Nov 2, 2011 at 23:53
Add a ment  | 

3 Answers 3

Reset to default 6
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

Change return this.attr('videofile'); to return $(this).attr('videofile');. You need to enclose the this in $() so it bees a jQuery object that you can then call attr() on.

Example: http://jsfiddle/r9xJn/

var result = $.map($('a.videoLink'), function(a) {
   return $(a).attr('videofile');
});

Working example: http://jsfiddle/hY6zM/

本文标签: jqueryJavascript array from all elements with a certain class nameStack Overflow