如何使输入通过单击更改其 src?

How can I make an input change its src with an onclick?

我正在尝试这个并且我的背景改变了颜色(我想要的)但是输入的 src 只在我第二次点击它时改变。我怎样才能让它在第一次点击时改变来源?另外,如何通过第二次单击将 src 更改回原始文件?

<input id="showHideContainer" type="image" src="on.png " height="3%" width="2%" alt="On" onclick="toggle();">

<script>
document.getElementById('showHideContainer').onclick = function () {
divTest = document.getElementById('header');
if (divTest.style.display === "none") {
    divTest.style.display = 'block';
} else {
    divTest.style.display = "none";
};
$('body').toggleClass('style2');
$('#showHideContainer').click(function(){
$('#showHideContainer').attr('src', 'off.png');
});
}
</script>

您需要确定 obj 的当前状态,然后将其与另一个切换

$('#showHideContainer').click(function(){
    var off = $(this).attr('src').indexOf('off.png')>-1;
    $(this).attr('src', (off?'on.png':'off.png'));
});

快速修复。您现在在第一次单击 #showHideContainer 时附加了另一个事件处理程序,这就是它没有第一次触发的原因。你的代码的这个修剪版本应该得到你预期的结果,另请参阅其他答案以查看你的元素属性的状态:

 document.getElementById('showHideContainer').onclick = function () {
        divTest = document.getElementById('header');
        if (divTest.style.display === "none") {
            divTest.style.display = 'block';
        } else {
            divTest.style.display = "none";
        };
        $('body').toggleClass('style2');
        var off = $(this).attr('src').indexOf('off.png')>-1;
        $(this).attr('src', (off?'on.png':'off.png'));
    }