jQuery get img source attributes from list and push into array

后端 未结 2 1592
青春惊慌失措
青春惊慌失措 2020-12-24 02:59

I have this thumbnail list and would like push the image paths (sources) into an array: tn_array

2条回答
  •  生来不讨喜
    2020-12-24 03:33

    You can create the array of src attributes more directly using map():

    var tn_array = $("#thumbnails img").map(function() {
      return $(this).attr("src");
    });
    

    Edit: tn_array is an object here rather than a strict Javascript array but it will act as an array. For example, this is legal code:

    for (int i=0; i

    You can however call get(), which will make it a strict array:

    var tn_array = $("#thumbnails img").map(function() {
      return $(this).attr("src");
    }).get();
    

    How do you tell the difference? Call:

    alert(obj.constructor.toString());
    

    The first version will be:

    function Object() { [native code] }
    

    The second:

    function Array() { [native code] }
    

提交回复
热议问题