开发者

Using jQuery to Grab Content

I'm trying to pull a couple variables from the following block of html. If you wouldn't mind helping, it would be greatly appreciated!

<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>

I'd like the function to traverse through #services and get the src values for each img, as well as the content from each <h2>.

This is what I have so far...

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


This should work. It is important to use the selector #services > div because each service div has a child div. Without the child selector you will get each service twice.

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


take a look at the find function

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

within the each function you can find what you need like this:

$(this).find('h2').text();
$(this).find('img').attr('src');


You're close.

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

Give that a shot.


I think you want this:

$("#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 is added so you always get a div with the correct elements.
  • We use > in the find function to grab the children (more efficient).
  • Remove the $this_html line if you don't need the entire HTML in addition to the h2/img, the latter stuff doesn't depend on it.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜