jquery img select

2020-07-22 18:43发布

问题:

I have a h4 with an img in it like this. I bind a click function to the h4. This works well. But I'm not able to select the img in it. I want to select the img in order to replage the src attr with .attr("src").replace("up", "down"); .

<h4 class="collapsable_head">
<img id="up_down" class="icon" src="/crm/img/modifier_down.gif" alt="link"/>
<b>Classification Filter:</b>
</h4>

The javascript:

$(".collapsable_head").click(function(){
   $(this).next(".collapsable_body").slideToggle(500)
   //None of the next lines return me the img object
   src = jQuery(this).children('img').attr("src");
   print(src);
   src = $(this).next("#up_down").attr("src");
   print(src);
   src = $(this).next("#up_down").attr("src");
   print(src);
   return false;
});

I want to use the keyword "this", since I have more (".collapsable_head")'s out there ;-)

回答1:

var img = $("img", this); // Gets the image within 'this'

The second parameter is the context of the selector. In full-code, it looks like this:

$(".collapsable_head").click(function(){
  var img = $("img:first", this).attr("src");
  alert(img);
});


回答2:

Did you try:

jQuery(this).find('img').attr('src')

Should do the same as Jonathans's answer.



回答3:

  $(function(){
      $("img").on('error', function() {
          $(this).attr('src',"/Files/446/178/themeblue/images/nopic.jpg");
      });   
 });