1

次の html ブロッ​​クからいくつかの変数を取得しようとしています。もしよろしければ、お役に立てれば幸いです。

<div id="services">
    <div id="service1">
      <div class="left">
        <img alt="Service Picture" src="/images/service-picture.jpg" />
        <h2 class="serviceHeading">A Beautiful Header</h2>
        <p>Some nice text.</p>
      </div>
      <div class="right">
        <p>Some more nice text.</p>
      </div>
      <br class="spacer"/>
      <a class="topButton" href="#" title="Back to Top">Back to Top</a>
    </div>
    <div id="service2">
      <div class="left">
        <img alt="Service Picture" src="/images/service-picture-2.jpg" />
        <h2 class="serviceHeading">Another Beautiful Header</h2>
        <p>Some even nicer text.</p>
      </div>
      <div class="right">
        <p>Some even more nicer text.</p>
      </div>
      <br class="spacer"/>
      <a class="topButton" href="#" title="Back to Top">Back to Top</a>
    </div>
  </div>

関数が走査して、 each のsrc値と、 eachのコンテンツ#services取得するようにしたいと思います。img<h2>

これは私がこれまでに持っているものです...

 $("#services div").each(function () {
   var $this_html = $(this).html();
   var h2_text = "";
   var img_src = "";
 });
4

4 に答える 4

3

これはうまくいくはずです。#services > div各サービス div には子 div があるため、セレクターを使用することが重要です。子セレクターがないと、各サービスを 2 回取得します。

$("#services > div").each(function () {
   var imgSrc= $(this).find('img').attr('src');
   var headerContent = $(this).find('h2').text();
});
于 2010-01-19T16:28:56.857 に答える
2

検索機能を見てみましょう

http://docs.jquery.com/Traversing/find

各関数内で、次のように必要なものを見つけることができます。

$(this).find('h2').text();
$(this).find('img').attr('src');
于 2010-01-19T16:20:46.627 に答える
1

あなたは近くにいます。

$("#services div").each(function () {
   var img_src= $(this).find('img').attr('src');
   var h2_text = $(this).find('h2').text();
 });

それを試してみてください。

于 2010-01-19T16:21:23.120 に答える
0

私はあなたがこれを望んでいると思います:

$("#services div.left").each(function () {
   var $this_html = $(this).html(); // don't know if you still want this
   var h2_text = $(this).find(">h2").text();
   var img_src = $(this).find(">img").attr("src");
 });
  • div.leftが追加されるため、常に正しい要素を含む div を取得できます。
  • 関数で使用>してfind、子を取得します (より効率的です)。
  • h2/img に加えて HTML 全体が必要ない場合は、この行を削除して$this_htmlください。後者はそれに依存しません。
于 2010-01-19T16:35:09.463 に答える