使用jQuery更改图像源

use*_*033 715 javascript jquery image

我的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>
Run Code Online (Sandbox Code Playgroud)

当有人点击图像上,我希望图像SRC切换到<img src="imgx_off.gif">其中x表示图像编号1或2.

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

jon*_*ohn 1617

您可以使用jQuery的attr()函数.例如,如果您的img代码的id属性为"my_image",则执行以下操作:

<img id="my_image" src="first.jpg"/>
Run Code Online (Sandbox Code Playgroud)

然后你可以src用这样的jQuery 改变你的图像:

$("#my_image").attr("src","second.jpg");
Run Code Online (Sandbox Code Playgroud)

要将此附加到click事件,您可以写:

$('#my_image').on({
    'click': function(){
        $('#my_image').attr('src','second.jpg');
    }
});
Run Code Online (Sandbox Code Playgroud)

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

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

  • 你应该***真的把这个标记为答案男人!不能比这更好...... (87认同)

Moh*_*sen 78

人们在更改图像源时常犯的错误之一就是不等待图像加载来执行后续操作,如成熟图像大小等.您需要使用jQuery .load()方法在图像加载后执行操作.

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

});
Run Code Online (Sandbox Code Playgroud)

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


kin*_*roi 22

如果您多次更新图像并且它被缓存并且没有更新,请在末尾添加一个随机字符串:

// update image in dom
$('#target').attr('src', 'https://example.com/img.jpg?rand=' + Math.random());
Run Code Online (Sandbox Code Playgroud)

  • 在末尾添加随机字符串非常重要,至少对我来说!坦克! (2认同)

小智 19

欲获得更多信息.我尝试使用以下语法在jquery中为广告图像设置src属性和attr方法:$("#myid").attr('src', '/images/sample.gif');

这个解决方案很有用,但是如果改变路径也改变了图像的路径而不工作.

我一直在寻找解决这个问题的方法,但一无所获.

解决方案是将'\'放在路径的开头: $("#myid").attr('src', '\images/sample.gif');

这个技巧对我来说非常有用,我希望它对其他人有用.


Pet*_*tai 17

我将向您展示如何更改图像src,以便当您单击图像时,它会旋转HTML中的所有图像(特别是您的d1ID和c1类中)... 您的HTML中是否有2个或更多图像.

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

完整的代码

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

    });
});
Run Code Online (Sandbox Code Playgroud)

细分

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

        var $images = $("#d1 > .c1 > a").clone();  ;
    
    Run Code Online (Sandbox Code Playgroud)
  2. 检查HTML中有多少图像,并创建一个变量来跟踪显示的图像:

    var $length = $images.length;
    var $imgShow = 0;
    
    Run Code Online (Sandbox Code Playgroud)
  3. 修改文档的HTML,以便显示第一个图像.删除所有其他图像.

    $("#d1 > .c1").html( $("#d1 > .c1 > a:first") ); 
    
    Run Code Online (Sandbox Code Playgroud)
  4. 绑定一个函数来处理单击图像链接的时间.

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

    上面代码的核心是++$imgShow % $length用于遍历包含图像的jQuery对象.++$imgShow % $length首先将我们的计数器增加1,然后根据有多少图像来修改该数字.这将使结果索引从0to 循环length-1,这是$images对象的索引.这意味着此代码将使用2,3,5,10或100个图像...按顺序循环显示每个图像,并在到达最后一个图像时在第一个图像处重新启动.

    另外,.attr()用于获取和设置图像的"src"属性.为了从$images对象中选择元素,我使用表单设置$imagesjQuery上下文$(selector, context).然后我用我.eq()选择具有我感兴趣的特定索引的元素.


jsFiddle示例有3张图片


您还可以将srcs 存储在数组中.
jsFiddle示例有3张图片

以下是如何将锚点标签中的hrefs合并到图像周围:
jsFiddle示例


小智 17

如果不仅有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';">
Run Code Online (Sandbox Code Playgroud)

这可以写成一般而且更优雅:

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


Zee*_*han 15

希望这可行

<img id="dummyimage" src="http://dummyimage.com/450x255/" alt="" />
<button id="changeSize">Change Size</button>
Run Code Online (Sandbox Code Playgroud)
$(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;
        }
    });
});
Run Code Online (Sandbox Code Playgroud)


Mr *_*map 12

您应该将id属性添加到图像标签,如下所示:

<div id="d1">
   <div class="c1">
            <a href="#"><img id="img1" src="img1_on.gif"></a>
            <a href="#"><img id="img2" src="img2_on.gif"></a>
   </div>
</div>
Run Code Online (Sandbox Code Playgroud)

那么您可以使用以下代码更改图像的来源:

 $(document).ready(function () {
        $("#img1").attr({ "src": "logo-ex-7.png" });
        $("#img2").attr({ "src": "logo-ex-8.png" });
    });
Run Code Online (Sandbox Code Playgroud)


Fer*_*her 9

你也可以用这种方式用jQuery做到这一点:

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

如果图像源有多个状态,则可以有条件.

  • 这种语法不对.jquery attr()函数需要1或2个参数.第一个是带有HTML属性名称的字符串,第二个是要设置的属性的值. (5认同)

Kay*_*ani 7

尝试调用重新验证按钮时,我遇到了同样的问题.经过一些搜索,现在几乎所有着名的浏览器(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);
 }
Run Code Online (Sandbox Code Playgroud)

'theUrl'用于渲染新的验证码图像,在您的情况下可以忽略.最重要的一点是生成新的URL,迫使FF和IE重新渲染图像.


小智 6

使用jQuery更改图像源 click()

元件:

    <img class="letstalk btn"  src="images/chatbuble.png" />
Run Code Online (Sandbox Code Playgroud)

码:

    $(".letstalk").click(function(){
        var newsrc;
        if($(this).attr("src")=="/images/chatbuble.png")
        {
            newsrc="/images/closechat.png";
            $(this).attr("src", newsrc);
        }
        else
        {
            newsrc="/images/chatbuble.png";
            $(this).attr("src", newsrc);
        }
    });
Run Code Online (Sandbox Code Playgroud)


Nei*_*yer 5

我在这里制作了一个具有此功能的代码笔。我也会在这里给你一个代码的细分。

代码笔

$(function() {

  //Listen for a click on the girl button
  $('#girl-btn').click(function() {

    // When the girl button has been clicked, change the source of the #square image to be the girl PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/girl.png");
  });

  //Listen for a click on the plane button
  $('#plane-btn').click(function() {

    // When the plane button has been clicked, change the source of the #square image to be the plane PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/airplane.png");
  });

  //Listen for a click on the fruit button
  $('#fruits-btn').click(function() {

    // When the fruits button has been clicked, change the source of the #square image to be the fruits PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/fruits.png");
  });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<img src="https://homepages.cae.wisc.edu/~ece533/images/girl.png" id="square" />
<div>
  <button id="girl-btn">Girl</button>
  <button id="plane-btn">Plane</button>
  <button id="fruits-btn">Fruits</button>

  <a href="https://homepages.cae.wisc.edu/~ece533/images/">Source of Images</a>
</div>
Run Code Online (Sandbox Code Playgroud)