在.map jQuery中循环

时间:2016-05-10 16:57:22

标签: jquery function

我需要获取所有span元素的ID,但是当我得到它时,我也需要获取图像的ID。

$('#showChild').append('Found <b>' + $('#Container > span').length + '</b> child SPAN elements <br />');

// SHOW THE CHILD DIV'S.
$('#Container > span').map(function() {
    $('#showChild').append(this.id + '<br />');
    alert(this.id);
    var id=this.id;
    alert(id);
    //CODE BELOW DOES NOT WORK
    $('#' + id + '> img').map(function() {
        $('#showChild').append(this.id + '<br />');
    });   
});

HTML

<div id="Container">
    <span id="Span1"></span>
    <img id="img1" />
    <img id="img2" />
    <span id="Span2"></span>
    <img id="img3" />
    <img id="img4" />
</div>

<!--DISPLAY THE CHILD DIV's-->
<div id="showChild"></div>

2 个答案:

答案 0 :(得分:0)

你需要使用兄弟姐妹()函数

  $(window).load(function () {
        $('#showChild').append('Found <b>' + $('#Container > span').length + '</b> child SPAN elements <br />');

// SHOW THE CHILD DIV'S.
        $('#Container > span').map(function() {
            $('#showChild').append(this.id + '<br />');
            alert(this.id);
            var id=this.id;
            alert(id);
            //CODE BELOW DOES NOT WORK
            $(this).siblings('img').map(function() {
                $('#showChild').append(this.id + '<br />');
            });
        });
    });

或者您可能需要将图像放在跨度内 不确定这是不是意图。

另一种方法

    $(window).load(function () {
        $('#showChild').append('Found <b>' + $('#Container > span').length + '</b> child SPAN elements <br />');

// SHOW THE CHILD DIV'S.
        $('#Container > span, #Container > img').map(function() {
            $('#showChild').append(this.id + '<br />');
            alert(this.id);
            var id=this.id;
            alert(id);

        });
    });

答案 1 :(得分:0)

img标签不在span元素内。你应该在span中添加img元素以使其工作。

 <div id="Container">
 <span id="Span1">
   <img id="img1" /><img id="img2" /></span>
 <span id="Span2"><img id="img3" /><img id="img4" /></span>
 </div>
 <!--DISPLAY THE CHILD DIV's-->
 <div id="showChild"></div>
相关问题