简体   繁体   English

如果页面上的任何复选框已选中或未选中,是否更改图像?

[英]Change image if any checkbox on the page was checked or unchecked?

I have a lot of checkboxes with different IDs on the page. 我在页面上有很多带有不同ID的复选框。

I want to change picture everytime when any checkbox was checked or unchecked... 我想每次选中或取消选中任何复选框时更改图片...

Please, tell me how to do that.. 请告诉我该怎么做..

The basic code is shown below. 基本代码如下所示。 Bind a onchange event to each input[type=checkbox] . onchange事件绑定到每个input[type=checkbox]

$(':checkbox').change(function(){
    $('#imgid').attr('src', 'newimg.png');
})

Pure JavaScript: 纯JavaScript:

var inputs = document.getElementsByTagName("input");
for(var i=inputs.length-1; i>=0; i--){ //Loop through each input element in the page
    var input = inputs[i];
    if(input.type == "checkbox"){
        input.onchange = function(){   //Bind `change` event handler
            document.getElementById("imgId").src = "newimg.png";
        }
    }
}

Note: The previously shown code snippets have to be called when the document has loaded. 注意:加载文档后,必须调用前面显示的代码段。 Either by using window.onload = function(){ /*Code here*/ } , or by adding the code at the end of the document. 通过使用window.onload = function(){ /*Code here*/ } ,或者通过在文档末尾添加代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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