2016-05-10 5 views
0

すべてのスパン要素のIDを取得する必要がありますが、取得する際には画像のIDも取得する必要があります。.map内のループjQuery

$('#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 />'); 
    }); 
}); 

あなたは兄弟()関数

$(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 />'); 
      }); 
     }); 
    }); 

またはあなたはそれが意図したかどうかわからない スパン内の画像を配置する必要がある場合がありますを使用する必要がある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> 
+1

'$( '#' + id + '> img')'の代わりに '$ '' id '' + img ')'が必要です。 'img'は' span'に隣接しています。それの子孫ではありません。 – haim770

答えて

0

別の方法

$(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); 

     }); 
    }); 
+0

ありがとうAceWeb; 出力は次のとおりです: はHTMLがある SPAN1 IMG1 IMG2 SPAN2 IMG3 IMG4 2つのSPAN要素を発見$( '#コンテナ>スパン、#Container> IMG')は、正しい結果を生成しました最初と同じです。 – ianWight

+0

私はこの文字列を生成する予定です:Span1 || img1 | img2 | Span2 || img3 | img4 | Ajax関数に渡します。これにより、ユーザーは実際にカテゴリであるスパン間で画像をドラッグアンドドロップできます。 – ianWight

+0

実際には文字列は || Span1 | img1 | img2 || Span2 | img3 | img4 | - .net分割で動作します。 – ianWight

0

IMGタグは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> 
関連する問題