javascript 通过单击图像选中复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4627265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:21:04  来源:igfitidea点击:

Checking a checkbox by clicking an image

javascript

提问by John

I have checkboxes under the thumbnails, here: http://jsfiddle.net/pAYFa/I want to do that by clicking the thumbnail, checkbox gets checked. I think this can be done with javascript, I'll appriciate any help in javascript. Thanks.

我在缩略图下有复选框,在这里:http: //jsfiddle.net/pAYFa/我想通过单击缩略图来做到这一点,复选框被选中。我认为这可以用 javascript 来完成,我会在 javascript 中提供任何帮助。谢谢。

回答by karim79

Just put the image into a label, and remove the duplicate IDs. I've done it for your first one: http://jsfiddle.net/karim79/pAYFa/1/

只需将图像放入标签中,然后删除重复的 ID。我已经为你的第一个完成了:http: //jsfiddle.net/karim79/pAYFa/1/

Each ID in the document must be uniqueas per the specification.

根据规范,文档中的每个 ID必须是唯一的。

回答by Spiny Norman

Well, the easiest way would be to put a label around your image. This will do exactly what you want:

嗯,最简单的方法是在图像周围贴上标签。这将完全符合您的要求:

<label for="img1"><img class="img" src="http://s5.tinypic.com/30v0ncn_th.jpg" /></label>
<input type="checkbox" class="chk " checked="checked" id="img1" name="img1" value="0" />

No javascript needed! You will have to remove your id="img1"from your <img>tag though, as you can't have more than one element with the same id.

不需要javascript!但是,您必须id="img1"<img>标签中删除您的标签,因为您不能拥有多个具有相同 ID 的元素。

回答by kemiller2002

As they answered above you don't need to do it through javascript, if you are curious about how to attach an event handler to the image. You do need to change the checkbox id to something other than what the image id is. I renamed it to chk2

正如他们在上面回答的那样,如果您对如何将事件处理程序附加到图像感到好奇,则不需要通过 javascript 来完成。您确实需要将复选框 id 更改为图像 id 以外的内容。我把它改名为chk2

document.getElementById('img2').onclick = function () //attach to onclick
{                             
        var checkbox = document.getElementById('chk2'); //find checkbox

        checkbox.checked = !checkbox.checked; //toggle the checked status
}

回答by Jamiec

With jQuery this is child's play:

使用 jQuery,这是孩子的游戏:

$('img').click(function(){
  $(this).next().click();
})

without, it becomes a little harder. I gave your checkboxes unique id's (img1_cb and img2_cb) and added a click handler to each image eg:

没有,它变得有点困难。我为您的复选框提供了唯一 ID(img1_cb 和 img2_cb),并为每个图像添加了一个点击处理程序,例如:

<img class="img" src="http://s5.tinypic.com/30v0ncn_th.jpg" id="img1" onclick="toggle('img1_cb')" />

Then the JavaScript was:

然后 JavaScript 是:

function toggle(what){
  var cb = document.getElementById(what);
  cb.checked = !cb.checked;  
}