Javascript array from all elements with a certain class name

╄→尐↘猪︶ㄣ 提交于 2020-01-02 10:06:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!