jquery img选择

Tho*_*mel 3 jquery jquery-selectors

我有一个带有img的h4就像这样.我将点击功能绑定到h4.这很好用.但是我无法在其中选择img.我想选择img以便用.attr("src")重放src attr.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>
Run Code Online (Sandbox Code Playgroud)

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;
});
Run Code Online (Sandbox Code Playgroud)

我想使用关键字"this",因为我有更多(".collapsable_head")在那里;-)

Sam*_*son 7

var img = $("img", this); // Gets the image within 'this'
Run Code Online (Sandbox Code Playgroud)

第二个参数是选择器的上下文.在完整代码中,它看起来像这样:

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


San*_*dro 6

你试过了吗:

jQuery(this).find('img').attr('src')
Run Code Online (Sandbox Code Playgroud)

应该像Jonathans的回答一样.