JavaScript,Jquery子节点迭代

时间:2013-05-15 17:55:35

标签: javascript jquery html

虽然我看到很多关于这个整体主题的帖子(best way to get child nodes)但我找不到关于双层嵌套子项中的迭代和赋值的任何内容。我在网上看到了用[]和()调用孩子的例子。提前谢谢。

假设我有这个HTML,并希望在“可排序”UL元素中包含所有文件名(不包括URL路径或文件扩展名)的字符串。

<ul id="sortable" class="ui-sortable">
    <li class="ui-state-default">
        <img id="aImg" alt="sortable image" src="images/a.jpg" />
    </li>
    <li class="ui-state-default">
        <img id="bImg" alt="sortable image" src="images/b.jpg" />
    </li>
    <li class="ui-state-default">
        <img id="cImg" alt="sortable image" src="images/c.jpg" />
    </li>
</ul>

我的JavaScript看起来像这样:

 var theImageOrder = "";
 var theCounter = 0;
 while (theCounter < $('#sortable').children().length) 
 {
    var theImageName = $('#sortable').children(theCounter).children(0).attr("src").toString().substring($('#sortable').children(theCounter).children(0).attr("src").toString().lastIndexOf("/") + 1, $('#sortable').children(theCounter).children(0).attr("src").toString().lastIndexOf("."));
    theImageOrder = theImageOrder + theImageName;
    theCounter++;
}

我希望输出结果是abc,但我得到了aaa。

4 个答案:

答案 0 :(得分:4)

UL应该只有LI子女,我猜测选择图像会很聪明,因为你正在寻找src属性。 $ .map返回数组中的每个元素,您可以选择将其连接以获取字符串。使用>确保它只是直接的孩子等:

var images = $.map($('#sortable > li > img'), function(el,i) {
    return el.src.split('/').pop();
}).join(', ');

FIDDLE

答案 1 :(得分:4)

var files = $('#sortable img').map(function(){
     return this.src.split('/').pop();
}).get();

http://jsfiddle.net/uyQXP/

答案 2 :(得分:1)

jQuery each()很可能是您正在寻找的答案。

var theImageOrder = "";
$('#sortable > li > img').each(function(index, element){
    theImageOrder += element.attr('src').howeverYouWantToModifyThisString();
});

答案 3 :(得分:1)

我在ES6中整理了一个可以帮助未来旁观者的一个vanilla JS递归示例:

let images = [];

const processChildrenNodes = (node, getNodeChildren) => {
  const nodeChildren = [...node.childNodes];

  for (const thisNode of nodeChildren) {
    if (getNodeChildren)
      processChildrenNodes(thisNode, true);

    if (thisNode.nodeName === 'IMG') {
      images.push(
        thisNode.getAttribute('src')
        .replace('.jpg', '')
        .split('/')
        .filter(item => item !== 'images')
      );
    }
  }
};

processChildrenNodes(document.getElementById('sortable'), true);

这将允许您查看IMG的所有节点子节点,然后将图像解析为&#34;图像&#34;阵列。这可以使用reduce进行更多压缩,但我认为如果没有Jquery,这将为您提供一个简单的选项。

上面的示例在JSFIDDLE

上进行了测试