jQuery を使用してコンテンツを取得する
-
21-09-2019 - |
質問
次の 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>
関数を横断したいのですが #services
そしてそれを手に入れてください 送信元 それぞれの値 img
, 、同様に コンテンツ それぞれから <h2>
.
これが私がこれまでに持っているものです...
$("#services div").each(function () {
var $this_html = $(this).html();
var h2_text = "";
var img_src = "";
});
解決
この作業をする必要があります。各サービスのdiv子div要素を持っているので、セレクタ#services > div
を使用することが重要です。子セレクタがなければ、あなたは二回、各サービスを取得します。
$("#services > div").each(function () {
var imgSrc= $(this).find('img').attr('src');
var headerContent = $(this).find('h2').text();
});
他のヒント
find関数を見てみましょう。
http://docs.jquery.com/Traversing/findする
あなたがこのように必要なものを見つけることができ、各関数内でます:
$(this).find('h2').text();
$(this).find('img').attr('src');
あなただ近います。
$("#services div").each(function () {
var img_src= $(this).find('img').attr('src');
var h2_text = $(this).find('h2').text();
});
与えるショットいる。
あなたはこれが欲しいと思います:
$("#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
子を取得する関数 (より効率的)。 - を削除します。
$this_html
h2/img に加えて HTML 全体が必要ない場合、後者はそれに依存しません。
所属していません StackOverflow