【问题标题】:jQuery create multidimensional array from multiple elementsjQuery从多个元素创建多维数组
【发布时间】:2014-02-19 21:45:13
【问题描述】:

如何为每个 li 类 sl-item 创建一个具有类似结构的多维数组:

$imagesList = [
   [1, 123, "<img src=\"/img-src/123.jpg \" />", "/photo/img-123", "image-alt "],
   [2, 452, "<img src=\"/img-src/452.jpg \" />", "/photo/img-452", "image-alt "],
];

首先应该只是数组的数量,1,2,3…,第二部分是li元素的id,第三是带有img src的img,第四是来自a的带有@类的url 987654326@,第五个是 img alt。 我的结构如下:

<ul class=”sl-img”>
    <li id=”123” class=”sl-item”>
        <a  class=”photo-url” href=”/photo/img-123”>
            <img alt=”image-alt” src=”/img-src/123.jpg” >
        </a>
    </li>
    <li id=”452” class=”sl-item”>
        <a  class=”photo-url” href=”/photo/img-452”>
            <img alt=”image-alt” src=”/img-src/452.jpg” >
        </a>
    </li>
    .....
</ul>

【问题讨论】:

  • 为什么需要数组中的数字?这不是被数组中的索引覆盖了吗?
  • 是的,它被索引覆盖了,你是对的,可以省略。

标签: jquery arrays multidimensional-array


【解决方案1】:

大概是这样的吧?

var result = [];

$('li').each(function(i){
    var $img = $(this).find('img');
    result.push([i+1, this.id, $img[0], $img.prop('src'), $img.prop('alt')]);
});

console.log(result);

我一开始尝试使用map(),但它似乎使数组变平。

http://jsfiddle.net/EX6Dt/

【讨论】:

    猜你喜欢
    • 2014-07-06
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    相关资源
    最近更新 更多