development

jQuery를 사용하여 이미지 소스 변경

big-blog 2020. 9. 30. 09:23
반응형

jQuery를 사용하여 이미지 소스 변경


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

누군가 이미지를 클릭하면 이미지 src가 이미지 번호 1 또는 2를 나타내는 <img src="imgx_off.gif">위치 로 변경되기를 원합니다 x.

이것이 가능합니까 아니면 이미지를 변경하기 위해 CSS를 사용해야합니까?


jQuery의 attr () 함수를 사용할 수 있습니다 . 예를 들어 img태그 id에 'my_image'속성 이있는 경우 다음을 수행합니다.

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

그런 다음 다음 src과 같이 jQuery로 이미지를 변경할 수 있습니다 .

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

이것을 click이벤트에 첨부하려면 다음과 같이 작성할 수 있습니다.

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

이미지를 회전하려면 다음을 수행하십시오.

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

사람들이 이미지 소스를 변경할 때 흔히 저지르는 실수 중 하나는 이미지로드가 이미지 크기 성숙 등의 작업을 수행하기 위해 이미지로드를 기다리지 않는 것입니다. 이미지로드 후에 작업을 수행하려면 jQuery .load()메소드를 사용해야 합니다.

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

});

편집 이유 : https://stackoverflow.com/a/670433/561545


자세한 내용은. 예를 들어 구문을 사용하여 광고 이미지에 대한 jquery에서 attr 메서드로 src 속성을 설정하려고합니다.$("#myid").attr('src', '/images/sample.gif');

이 솔루션은 유용하고 작동하지만 경로를 변경하면 이미지의 경로도 변경되고 작동하지 않습니다.

이 문제를 해결하기 위해 검색했지만 아무것도 찾지 못했습니다.

해결책은 경로 시작 부분에 '\'를 넣는 것입니다. $("#myid").attr('src', '\images/sample.gif');

이 트릭은 저에게 매우 유용하며 다른 사람들에게도 유용하기를 바랍니다.


나는 어떻게 이미지를 변경하는 방법을 보여 드리겠습니다 src, 그래서 당신은 (당신의 당신의 HTML에있는 모든 이미지를 회전 이미지를 클릭하면 d1ID와 c1특별히 클래스) ... 당신이이 개 있는지 이상의 이미지 를 HTML의를 .

또한 문서가 준비된 후 페이지를 정리하여 처음에 하나의 이미지 만 표시되도록하는 방법도 보여 드리겠습니다.

전체 코드

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

    });
});

고장

  1. 이미지가 포함 된 링크의 사본을 만듭니다 (참고 : 추가 기능을 위해 링크의 href 속성을 사용할 수도 있습니다 ... 예를 들어 각 이미지 아래에 작동하는 링크 표시 ).

        var $images = $("#d1 > .c1 > a").clone();  ;
    
  2. 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.

    $("#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.

    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.


jsFiddle example with 3 images


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

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


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(!):

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

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

You can also do this with jQuery in this way:

$(".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.


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,...):

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.


You should add id attribute to your image tag, like this:

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

then you can use this code to change the source of images:

 $(document).ready(function () {
        doSomething();
        $("#img1").attr({ "src": "logo-ex-7.png" });
        $("#img2").attr({ "src": "logo-ex-8.png" });
    });

Change the image source using jQuery click()

element:

    <img class="letstalk btn"  src="images/chatbuble.png" />

code:

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

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

This is a guaranteed way to get it done in Vanilla (or simply Pure) JavaScript:

var picurl = 'pictures/apple.png';
document.getElementById("image_id").src=picurl;

Just an addition, to make it even more tiny:

$('#imgId').click(function(){
    $(this).attr("src",$(this).attr('src') == 'img1_on.gif' ? 'img1_off.gif':'img1_on.gif');
});

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

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

Logic-

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

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

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

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>

참고URL : https://stackoverflow.com/questions/554273/changing-the-image-source-using-jquery

반응형