简体   繁体   中英

how to change image(img URL is everytime coming from the server) on button click in html

I am new in client side scripting as well as stackoverflow. I want to change an image(Image URL is coming from the server everytime) of a div on click of a button or anchor. Here is My code for changing image.

$scope.captchaChange = function () {
    $http({
        method: "POST",
        url: 'http://localhost:8080/Project/captcha/captcha',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    }).success(function (response) {
        if (response.imgUrl.length > 0) {
            document.getElementById("captchaImg").src = response.imgUrl;
            document.getElementById("captchatext").value = response.imgToken;
        } else {
            alert('no captcha Image Avalable');
        }
    }).error(function (response) {
        //alert("response" + response)
        $scope.codeStatus = response || "Request failed";
        return false;
    });
}

Assuming you're trying to load a new image from the server and replace the current image in the div, you can do it like this:

 $('#img-change-btn').click(function() {
    var path = response.imgUrl // Or some path;
    $('#img-display-div img').attr('src', path)
                         .attr('alt', $('img', this).attr('title')); 
});

Here's working code: http://jsfiddle.net/yV6e6/6/

Note: I've used a bit of JQuery (.click, .empty,.append, etc), you can remove that and use only Javascript if you aren't using the JQuery Library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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