简体   繁体   English

用jquery更改img src

[英]changing the img src with jquery

The html structure I have is something like: 我有的html结构是这样的:

<ul id="something">
  <li>
    <a href="">
      <img src="http://domain.com/directory/file1-128x79.jpg">
    </a>
  </li>
  <li>
    <a href="">
      <img src="http://domain.com/directory/file2-128x79.jpg">
    </a>
  </li>
  <li>
    <a href="">
      <img src="http://domain.com/directory/file3-128x79.jpg">
    </a>
  </li>
</ul>

I'm trying to change the filename from file#-128x79.jpg to file#-896x277.jpg . 我正在尝试将文件名从文件#-128x79.jpg更改文件#-896x277.jpg

I don't know how to take the dynamically generated filename and search and replace for the src changes. 我不知道如何获取动态生成的文件名并搜索和替换src更改。

I found my way to replacing the whole src with 'none' to make sure I got it right so far, but I don't know how to do the rest. 我找到了用'none'替换整个src的方法,以确保我到目前为止做到了,但我不知道如何做其余的事情。

$('#something').removeAttr('id').prop('class', 'some-class').find('img').prop('src', 'none');

You can replace the src for each img by first selecting all the images with a selector and then using the attr callback to replace the contents: 您可以通过首先使用选择器选择所有图像,然后使用attr回调replace内容来replace每个imgsrc

$('#something img').attr('src',function(i,e){
    return e.replace("-128x79.jpg","-896x277.jpg");
})

you can assign an id to your image tag like 你可以为你的图片标签指定一个id

<img id ="pic" src="http://domain.com/directory/file3-128x79.jpg">

then in jquery use 然后在jquery中使用

$('#pic').attr('src', 'file#-896x277.jpg');

DEMO DEMO

$('img').hover(function(){ // or any other method
    this.src = this.src.replace("128x79", "200x60");         
}); 

您应该添加.children()之前.find('img')

$('#something').removeAttr('id').attr('class', 'some-class').children().find('img').attr('src', 'none');

Note : try the following here mouse over is just for the demo purpose only 注意:请尝试以下鼠标,仅用于演示目的

$(function() {
    $("something li a img")
        .mouseover(function() { 
            var src = "over.gif";
            $(this).attr("src", src); // change the image source
        })

});

使用attr怎么样:

this.removeAttr('id').prop('class', 'featured-images').find('img').attr({‘src’:'file#-896x277.jpg’});
$('#something img').attr('src',$('#something img').attr('src').replace(x,y))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM