jquery img 选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2023453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:36:10  来源:igfitidea点击:

jquery img select

jqueryjquery-selectors

提问by Thomas Kremmel

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"); .

我有一个像这样带有 img 的 h4。我将点击功能绑定到 h4。这很好用。但我无法选择其中的 img。我想选择 img 以便用 .attr("src").replace("up", "down"); 替换 src attr。.

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

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

我想使用关键字“this”,因为我还有更多(“.collapsable_head”);-)

回答by Sampson

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);
});

回答by Sandro

Did you try:

你试过了吗:

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

Should do the same as Jonathans's answer.

应该和乔纳森的回答一样。

回答by M.Ganji

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