如何在 HTML 中的按钮单击上更改图像(IMG URL 每次来自服务器)

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

本文关键字:URL IMG 服务器 图像 HTML 按钮 单击      更新时间:2023-09-26

我是客户端脚本和堆栈溢出的新手。我想在单击按钮或锚点时更改div 的图像(图像 URL 每次都来自服务器)。这是我更改图像的代码。

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

假设您尝试从服务器加载新图像并替换div 中的当前图像,您可以这样做:

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

这是工作代码:http://jsfiddle.net/yV6e6/6/

注意:我使用了一点JQuery(.click,.empty,.append等),如果你不使用JQuery库,你可以删除它并只使用Javascript。