使用jQuery修改图像源

时间:2022-11-28 21:46:12

My DOM looks like this:

我的DOM是这样的:

<div id="d1">
   <div class="c1">
            <a href="#"><img src="img1_on.gif"></a>
            <a href="#"><img src="img2_on.gif"></a>
   </div>
</div>

When someone clicks on an image, I want the image src to change to <img src="imgx_off.gif"> where x represents the image number 1 or 2.

当有人单击图像时,我希望图像src更改为使用jQuery修改图像源,其中x代表图像1或2。

Is this possible or do I have to use CSS to change the images?

这可能吗?还是我必须使用CSS来修改图像?

10 个解决方案

#1


1340  

You can use jQuery's attr() function. For example, if you img tag has an id attribute of 'my_image':

您可以使用jQuery的attr()函数。例如,如果您的img标记具有“my_image”的id属性:

<img id="my_image" src="first.jpg"/>

Then you can change the src in jQuery by:

然后您可以在jQuery中更改src:

$("#my_image").attr("src","second.jpg");

To attach this to a click event, you could write:

要将其附加到单击事件,您可以编写:

$('#my_image').on({
    'click': function(){
        $('#my_image').attr('src','second.jpg');
    }
});

To rotate the image, you could do this:

要旋转图像,可以这样做:

$('img').on({
    'click': function() {
         var src = ($(this).attr('src') === 'img1_on.jpg')
            ? 'img2_on.jpg'
            : 'img1_on.jpg';
         $(this).attr('src', src);
    }
});

#2


68  

One of the common mistakes people do when change the image source is not waiting for image load to do afterward actions like maturing image size etc. You will need to use jQuery .load() method to do stuff after image load.

当更改图像源时,人们通常会犯的一个错误是不等待图像加载完成之后的操作,比如图像尺寸逐渐变大等。

$('yourimageselector').attr('src', 'newsrc').load(function(){
    this.width;   // Note: $(this).width() will not work for in memory images

});

Reason for editing: https://*.com/a/670433/561545

编辑的原因:https://*.com/a/670433/561545

#3


18  

For more information. I try setting src attribute with attr method in jquery for ad image using the syntax for example: $("#myid").attr('src', '/images/sample.gif');

为更多的信息。我尝试用jquery的attr方法将src属性设置为ad图像,例如:$(“#myid”)。attr(“src”、“/图片/ sample.gif”);

This solution is useful and it works but if changing the path change also the path for image and not working.

这个解决方案是有用的,它可以工作,但是如果改变路径,也可以改变图像的路径而不工作。

I've searching for resolve this issue but not found nothing.

我一直在寻找解决这个问题的办法,但是一无所获。

The solution is putting the '\' at the beginning the path: $("#myid").attr('src', '\images/sample.gif');

解决方案是将'\'放在路径的开头:$(“#myid”)。attr(“src”、“\图片/ sample.gif”);

This trick is very useful for me and I hope it is useful for other.

这个技巧对我很有用,我希望它对别人有用。

#4


15  

I'll show you how to change the image src, so that when you click an image it rotates through all the images that are in your HTML (in your d1 id and c1 class specifically)... whether you have 2 or more images in your HTML.

我将向您展示如何更改图像src,以便当您单击一个图像时,它将在HTML(尤其是d1 id和c1类)中的所有图像中旋转……在HTML中是否有两个或多个图像。

I'll also show you how to clean up the page after the document is ready, so that only one image is displayed initially.

我还将向您展示如何在文档准备好之后清理页面,以便最初只显示一个图像。

The full code

完整的代码

$(function() {

    var $images = $("#d1 > .c1 > a").clone();  

    var $length = $images.length;
    var $imgShow = 0;

    $("#d1 > .c1").html( $("#d1 > .c1 > a:first") );  

    $("#d1 > .c1 > a").click(function(event) { 

        $(this).children().attr("src", 
                        $("img", $images).eq(++$imgShow % $length).attr("src") );
        event.preventDefault();

    });
});

The breakdown

分解

  1. Create a copy of the links containing the images (note: you could also make use of the href attribute of the links for added functionality... for example display the working link below each image):

    创建包含图像的链接的副本(注意:您还可以使用链接的href属性来添加功能……例如显示每个图像下面的工作链接):

        var $images = $("#d1 > .c1 > a").clone();  ;
    
  2. Check how many images were in the HTML and create a variable to track which image is being shown:

    检查HTML中有多少图像,并创建一个变量来跟踪显示哪个图像:

    var $length = $images.length;
    var $imgShow = 0;
    
  3. Modify the document's HTML so that only the first image is being shown. Delete all the other images.

    修改文档的HTML,以便只显示第一个图像。删除所有其他图像。

    $("#d1 > .c1").html( $("#d1 > .c1 > a:first") ); 
    
  4. Bind a function to handle when the image link is clicked.

    当点击图像链接时,绑定一个函数来处理。

        $("#d1 > .c1 > a").click(function(event) { 
            $(this).children().attr("src", $("img", $images).eq(++$imgShow % $length).attr("src") );
            event.preventDefault();
        });
    

    The heart of the above code is using ++$imgShow % $length to cycle through the jQuery object containing the images. ++$imgShow % $length first increases our counter by one, then it mods that number with how many images there are. This will keep the resultant index cycling from 0 to length-1, which are the indices of the $images object. This means this code will work with 2, 3, 5, 10, or 100 images... cycling through each image in order and restarting at the first image when the last image is reached.

    上述代码的核心是使用++$imgShow % $length循环遍历包含图像的jQuery对象。++$imgShow % $length首先增加我们的计数器,然后它将这个数字与有多少个图像联系在一起。这将使合成索引从0循环到length-1,这是$images对象的索引。这意味着该代码可以处理2、3、5、10或100个图像……按顺序循环遍历每个图像,并在到达最后一个图像时重新启动第一个图像。

    Additionally, .attr() is used to get and set the "src" attribute of the images. To pick elements from among the $images object, I set $images as the jQuery context using the form $(selector, context). Then I use .eq() to pick just the element with the specific index I'm interested in.

    此外,.attr()用于获取和设置图像的“src”属性。要从$images对象中选择元素,我使用表单$(选择器、上下文)将$images设置为jQuery上下文。然后我使用。eq()来选择我感兴趣的特定索引的元素。


jsFiddle example with 3 images


You can also store the srcs in an array.
jsFiddle example with 3 images

您还可以将srcs存储在一个数组中。jsFiddle示例包含3幅图像

And here's how to incorporate the hrefs from the anchor tags around the images:
jsFiddle example

下面是如何从图像周围的锚标记合并hrefs: jsFiddle示例

#5


11  

IF there is not only jQuery or other resource killing frameworks - many kb to download each time by each user just for a simple trick - but also native JavaScript(!):

如果不仅有jQuery或其他资源杀伤框架(每个用户为了一个简单的技巧每次都要下载许多kb),还有本地JavaScript(!):

<img src="img1_on.jpg" 
    onclick="this.src=this.src.match(/_on/)?'img1_off.jpg':'img1_on.jpg';">
<img src="img2_on.jpg" 
    onclick="this.src=this.src.match(/_on/)?'img2_off.jpg':'img2_on.jpg';">

This can be written general and more elegant:

这可以写得更一般更优雅:

<html>
<head>
<script>
function switchImg(img){
    img.src = img.src.match(/_on/) ? 
        img.src.replace(/_on/, "_off") : 
        img.src.replace(/_off/, "_on");
}
</script>
</head>
<body>
    <img src="img1_on.jpg" onclick="switchImg(this)">
    <img src="img2_on.jpg" onclick="switchImg(this)">
</body>
</html>

#6


7  

You can also do this with jQuery in this way:

你也可以用jQuery这样做:

$(".c1 img").click(function(){
     $(this).attr('src','/new/image/src.jpg');   
});

You can have a condition if there are multiple states for the image source.

如果映像源有多个状态,则可以有一个条件。

#7


5  

I had the same problem when trying to call re captcha button. After some searching, now the below function works fine in almost all the famous browsers(chrome,Firefox,IE,Edge,...):

我在试图调用re captcha按钮时遇到了同样的问题。在搜索之后,现在几乎所有著名的浏览器(chrome,Firefox,IE,Edge,…)都可以使用下面的功能:

function recaptcha(theUrl) {
  $.get(theUrl, function(data, status){});
  $("#captcha-img").attr('src', "");
  setTimeout(function(){
       $("#captcha-img").attr('src', "captcha?"+new Date().getTime());
  }, 0);
 }

'theUrl' is used to render new captcha image and can be ignored in your case. The most important point is generating new URL which forces FF and IE to rerender the image.

“theUrl”用于呈现新的验证码图像,在您的示例中可以忽略。最重要的一点是生成新的URL,使FF和IE重新运行图像。

#8


3  

I have the same wonder today, I did on this way :

我今天也有同样的惊奇,我就是这样做的:

//<img src="actual.png" alt="myImage" class=myClass>
$('.myClass').attr('src','').promise().done(function() {
$(this).attr('src','img/new.png');  
});

#9


0  

There is no way of changing the image source with CSS.

用CSS改变图像源是不可能的。

Only possible way is using Javascript or any Javascript library like jQuery.

唯一可能的方法是使用Javascript或jQuery之类的任何Javascript库。

Logic-

The images are inside a div and there are no class or id with that image.

图像在div中,并且没有具有该图像的类或id。

So logic will be select the elements inside the div where the images are located.

因此,逻辑将选择div中图像所在的元素。

Then select all the images elements with loop and change the image src with Javascript / jQuery.

然后使用循环选择所有的图像元素,并用Javascript / jQuery修改图像src。

Example Code with demo output-

$(document).ready(function()
{
    $("button").click(function()
    {
      $("#d1 .c1 a").each(function()
      {
          $(this).children('img').attr('src', 'https://www.gravatar.com/avatar/e56672acdbce5d9eda58a178ade59ffe');
      });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<div id="d1">
   <div class="c1">
            <a href="#"><img src="img1_on.gif"></a>
            <a href="#"><img src="img2_on.gif"></a>
   </div>
</div>

<button>Change The Images</button>

#10


0  

Hope this can work

希望这能

<img id="dummyimage" src="http://dummyimage.com/450x255/" alt="" />
<button id="changeSize">Change Size</button>

$(document).ready(function(){
var flag = 0;
$("button#changeSize").click(function(){
if(flag == 0) {
  $("#dummyimage").attr("src","http://dummyimage.com/250x155/");
  flag = 1;
}
else if(flag == 1) {
  $("#dummyimage").attr("src","http://dummyimage.com/450x255/");
  flag = 0;
}
});
});

#1


1340  

You can use jQuery's attr() function. For example, if you img tag has an id attribute of 'my_image':

您可以使用jQuery的attr()函数。例如,如果您的img标记具有“my_image”的id属性:

<img id="my_image" src="first.jpg"/>

Then you can change the src in jQuery by:

然后您可以在jQuery中更改src:

$("#my_image").attr("src","second.jpg");

To attach this to a click event, you could write:

要将其附加到单击事件,您可以编写:

$('#my_image').on({
    'click': function(){
        $('#my_image').attr('src','second.jpg');
    }
});

To rotate the image, you could do this:

要旋转图像,可以这样做:

$('img').on({
    'click': function() {
         var src = ($(this).attr('src') === 'img1_on.jpg')
            ? 'img2_on.jpg'
            : 'img1_on.jpg';
         $(this).attr('src', src);
    }
});

#2


68  

One of the common mistakes people do when change the image source is not waiting for image load to do afterward actions like maturing image size etc. You will need to use jQuery .load() method to do stuff after image load.

当更改图像源时,人们通常会犯的一个错误是不等待图像加载完成之后的操作,比如图像尺寸逐渐变大等。

$('yourimageselector').attr('src', 'newsrc').load(function(){
    this.width;   // Note: $(this).width() will not work for in memory images

});

Reason for editing: https://*.com/a/670433/561545

编辑的原因:https://*.com/a/670433/561545

#3


18  

For more information. I try setting src attribute with attr method in jquery for ad image using the syntax for example: $("#myid").attr('src', '/images/sample.gif');

为更多的信息。我尝试用jquery的attr方法将src属性设置为ad图像,例如:$(“#myid”)。attr(“src”、“/图片/ sample.gif”);

This solution is useful and it works but if changing the path change also the path for image and not working.

这个解决方案是有用的,它可以工作,但是如果改变路径,也可以改变图像的路径而不工作。

I've searching for resolve this issue but not found nothing.

我一直在寻找解决这个问题的办法,但是一无所获。

The solution is putting the '\' at the beginning the path: $("#myid").attr('src', '\images/sample.gif');

解决方案是将'\'放在路径的开头:$(“#myid”)。attr(“src”、“\图片/ sample.gif”);

This trick is very useful for me and I hope it is useful for other.

这个技巧对我很有用,我希望它对别人有用。

#4


15  

I'll show you how to change the image src, so that when you click an image it rotates through all the images that are in your HTML (in your d1 id and c1 class specifically)... whether you have 2 or more images in your HTML.

我将向您展示如何更改图像src,以便当您单击一个图像时,它将在HTML(尤其是d1 id和c1类)中的所有图像中旋转……在HTML中是否有两个或多个图像。

I'll also show you how to clean up the page after the document is ready, so that only one image is displayed initially.

我还将向您展示如何在文档准备好之后清理页面,以便最初只显示一个图像。

The full code

完整的代码

$(function() {

    var $images = $("#d1 > .c1 > a").clone();  

    var $length = $images.length;
    var $imgShow = 0;

    $("#d1 > .c1").html( $("#d1 > .c1 > a:first") );  

    $("#d1 > .c1 > a").click(function(event) { 

        $(this).children().attr("src", 
                        $("img", $images).eq(++$imgShow % $length).attr("src") );
        event.preventDefault();

    });
});

The breakdown

分解

  1. Create a copy of the links containing the images (note: you could also make use of the href attribute of the links for added functionality... for example display the working link below each image):

    创建包含图像的链接的副本(注意:您还可以使用链接的href属性来添加功能……例如显示每个图像下面的工作链接):

        var $images = $("#d1 > .c1 > a").clone();  ;
    
  2. Check how many images were in the HTML and create a variable to track which image is being shown:

    检查HTML中有多少图像,并创建一个变量来跟踪显示哪个图像:

    var $length = $images.length;
    var $imgShow = 0;
    
  3. Modify the document's HTML so that only the first image is being shown. Delete all the other images.

    修改文档的HTML,以便只显示第一个图像。删除所有其他图像。

    $("#d1 > .c1").html( $("#d1 > .c1 > a:first") ); 
    
  4. Bind a function to handle when the image link is clicked.

    当点击图像链接时,绑定一个函数来处理。

        $("#d1 > .c1 > a").click(function(event) { 
            $(this).children().attr("src", $("img", $images).eq(++$imgShow % $length).attr("src") );
            event.preventDefault();
        });
    

    The heart of the above code is using ++$imgShow % $length to cycle through the jQuery object containing the images. ++$imgShow % $length first increases our counter by one, then it mods that number with how many images there are. This will keep the resultant index cycling from 0 to length-1, which are the indices of the $images object. This means this code will work with 2, 3, 5, 10, or 100 images... cycling through each image in order and restarting at the first image when the last image is reached.

    上述代码的核心是使用++$imgShow % $length循环遍历包含图像的jQuery对象。++$imgShow % $length首先增加我们的计数器,然后它将这个数字与有多少个图像联系在一起。这将使合成索引从0循环到length-1,这是$images对象的索引。这意味着该代码可以处理2、3、5、10或100个图像……按顺序循环遍历每个图像,并在到达最后一个图像时重新启动第一个图像。

    Additionally, .attr() is used to get and set the "src" attribute of the images. To pick elements from among the $images object, I set $images as the jQuery context using the form $(selector, context). Then I use .eq() to pick just the element with the specific index I'm interested in.

    此外,.attr()用于获取和设置图像的“src”属性。要从$images对象中选择元素,我使用表单$(选择器、上下文)将$images设置为jQuery上下文。然后我使用。eq()来选择我感兴趣的特定索引的元素。


jsFiddle example with 3 images


You can also store the srcs in an array.
jsFiddle example with 3 images

您还可以将srcs存储在一个数组中。jsFiddle示例包含3幅图像

And here's how to incorporate the hrefs from the anchor tags around the images:
jsFiddle example

下面是如何从图像周围的锚标记合并hrefs: jsFiddle示例

#5


11  

IF there is not only jQuery or other resource killing frameworks - many kb to download each time by each user just for a simple trick - but also native JavaScript(!):

如果不仅有jQuery或其他资源杀伤框架(每个用户为了一个简单的技巧每次都要下载许多kb),还有本地JavaScript(!):

<img src="img1_on.jpg" 
    onclick="this.src=this.src.match(/_on/)?'img1_off.jpg':'img1_on.jpg';">
<img src="img2_on.jpg" 
    onclick="this.src=this.src.match(/_on/)?'img2_off.jpg':'img2_on.jpg';">

This can be written general and more elegant:

这可以写得更一般更优雅:

<html>
<head>
<script>
function switchImg(img){
    img.src = img.src.match(/_on/) ? 
        img.src.replace(/_on/, "_off") : 
        img.src.replace(/_off/, "_on");
}
</script>
</head>
<body>
    <img src="img1_on.jpg" onclick="switchImg(this)">
    <img src="img2_on.jpg" onclick="switchImg(this)">
</body>
</html>

#6


7  

You can also do this with jQuery in this way:

你也可以用jQuery这样做:

$(".c1 img").click(function(){
     $(this).attr('src','/new/image/src.jpg');   
});

You can have a condition if there are multiple states for the image source.

如果映像源有多个状态,则可以有一个条件。

#7


5  

I had the same problem when trying to call re captcha button. After some searching, now the below function works fine in almost all the famous browsers(chrome,Firefox,IE,Edge,...):

我在试图调用re captcha按钮时遇到了同样的问题。在搜索之后,现在几乎所有著名的浏览器(chrome,Firefox,IE,Edge,…)都可以使用下面的功能:

function recaptcha(theUrl) {
  $.get(theUrl, function(data, status){});
  $("#captcha-img").attr('src', "");
  setTimeout(function(){
       $("#captcha-img").attr('src', "captcha?"+new Date().getTime());
  }, 0);
 }

'theUrl' is used to render new captcha image and can be ignored in your case. The most important point is generating new URL which forces FF and IE to rerender the image.

“theUrl”用于呈现新的验证码图像,在您的示例中可以忽略。最重要的一点是生成新的URL,使FF和IE重新运行图像。

#8


3  

I have the same wonder today, I did on this way :

我今天也有同样的惊奇,我就是这样做的:

//<img src="actual.png" alt="myImage" class=myClass>
$('.myClass').attr('src','').promise().done(function() {
$(this).attr('src','img/new.png');  
});

#9


0  

There is no way of changing the image source with CSS.

用CSS改变图像源是不可能的。

Only possible way is using Javascript or any Javascript library like jQuery.

唯一可能的方法是使用Javascript或jQuery之类的任何Javascript库。

Logic-

The images are inside a div and there are no class or id with that image.

图像在div中,并且没有具有该图像的类或id。

So logic will be select the elements inside the div where the images are located.

因此,逻辑将选择div中图像所在的元素。

Then select all the images elements with loop and change the image src with Javascript / jQuery.

然后使用循环选择所有的图像元素,并用Javascript / jQuery修改图像src。

Example Code with demo output-

$(document).ready(function()
{
    $("button").click(function()
    {
      $("#d1 .c1 a").each(function()
      {
          $(this).children('img').attr('src', 'https://www.gravatar.com/avatar/e56672acdbce5d9eda58a178ade59ffe');
      });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<div id="d1">
   <div class="c1">
            <a href="#"><img src="img1_on.gif"></a>
            <a href="#"><img src="img2_on.gif"></a>
   </div>
</div>

<button>Change The Images</button>

#10


0  

Hope this can work

希望这能

<img id="dummyimage" src="http://dummyimage.com/450x255/" alt="" />
<button id="changeSize">Change Size</button>

$(document).ready(function(){
var flag = 0;
$("button#changeSize").click(function(){
if(flag == 0) {
  $("#dummyimage").attr("src","http://dummyimage.com/250x155/");
  flag = 1;
}
else if(flag == 1) {
  $("#dummyimage").attr("src","http://dummyimage.com/450x255/");
  flag = 0;
}
});
});