使用jquery从图像列表中创建数组

时间:2010-04-19 17:03:35

标签: php jquery image arrays

我有一张像这样的照片列表:

<div class="upimage">
    <ul id="upimagesQueue" class="thumbs ui-sortable">
    <li id="upimagesKHGYUD">
        <a href="uploads/0002.jpg">
            <img src="uploads/0002.jpg" id="KHGYUD">
        </a>
    </li>
    <li id="upimagesNCEEKI">
        <a href="uploads/0003.jpg">
            <img src="uploads/0003.jpg" id="NCEEKI">
        </a>
    </li>
    <li id="upimagesPWSHUN">
        <a href="uploads/0003.jpg">
            <img src="uploads/0003.jpg" id="PWSHUN">
        </a>
    </li>
    <li id="upimagesOYJAQV">
        <a href="uploads/0004.jpg">
            <img src="uploads/0004.jpg" id="OYJAQV">
        </a>
    </li>
    </ul>
</div>

我想在jquery中创建一个函数也可以获得1个数组中的所有图像,以便能够将数组发送到php!我想要以这种形式的数组:

array(
    'image_id_1' => array(
        'image_src_1' => 'xyz.jpg',
    )
    'image_id_2' => array(
        'image_src_2' => 'xyz.jpg',
    )
    'image_id_3' => array(
        'image_src_3' => 'xyz.jpg',
    )
    'image_id_4' => array(
        'image_src_4' => 'xyz.jpg',
    )
)

我怎么能编码呢? 感谢

3 个答案:

答案 0 :(得分:5)

var a = {};
$(".upimage img").each(function() {
  a[this.id] = $(this).attr("src");
});

会给你

a = {
  "KHGYUD": "uploads/0002.jpg",
  "NCEEKI": "uploads/0003.jpg",
  "PWSHUN": "uploads/0003.jpg",
  "OYJAQV": "uploads/0004.jpg"
};

不确定为什么要使用多维数组。

答案 1 :(得分:0)

var images = {};
$('.upimage li').each(function(){
  var $img   = $(this).find('img'),
      imgObj = {};

  imgObj[$img.attr('src')] = $img.attr('id');
  images[$(this).attr('id')] = imgObj;
});

// Then to send to php
$.post('url', images, function(){ /* success */ });

(看起来你有两次图片src,所以我只是假设你的意思是首先是图像src,无论哪种方式,这都是一个很小的变化)

答案 2 :(得分:0)

<强>已更新

DEMO: hhttp://jsbin.com/idovi3/6

你问jQUERY PLUGIN是什么; - )

(function($) {

    $.fn.serializeImages = function() {
       //create the array...
       var toReturn    = [];
       //get the LI
       var els = $(this);
       //loop trought each LI ...
        $.each(els, function(i) {
         //get the Li id...
        var id = $(this).children().children().attr('id');
         //get the img src of the parent A parent IMG...
        var val = $(this).children().children().attr('src').split('uploads/')[1];
         //put each item in the array...
        toReturn.push( 
         // format the array...         
        id + ' => array( "image_src_' + i + '"' + ' => ' + val  + ', )'

            );           
        });   
        //join all into one single var for easy access.. 
        // \n can be whatever you want      
        var array =  toReturn.join('\n');

        return array; 
    }

})(jQuery);

  $(function () {
    var serie = $('ul li').serializeImages();
    alert(serie); 
  });

<强> ECHO:

KHGYUD => array( "image_src_0" => 0002.jpg, )
NCEEKI => array( "image_src_1" => 0003.jpg, )
PWSHUN => array( "image_src_2" => 0003.jpg, )
OYJAQV => array( "image_src_3" => 0004.jpg, )