简体   繁体   English

单击图像选中复选框

[英]Checking a checkbox by clicking an image

I have checkboxes under the thumbnails, here: http://jsfiddle.net/pAYFa/ I want to do that by clicking the thumbnail, checkbox gets checked. 我在缩略图下面有复选框,这里: http//jsfiddle.net/pAYFa/我想通过点击缩略图,复选框进行检查。 I think this can be done with javascript, I'll appriciate any help in javascript. 我认为这可以通过javascript完成,我会在javascript中使用任何帮助。 Thanks. 谢谢。

Just put the image into a label, and remove the duplicate IDs. 只需将图像放入标签,然后删除重复的ID。 I've done it for your first one: http://jsfiddle.net/karim79/pAYFa/1/ 我已经完成了你的第一个: http//jsfiddle.net/karim79/pAYFa/1/

Each ID in the document must be unique as per the specification . 根据规范 ,文档中的每个ID 必须是唯一的。

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! 不需要javascript! 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. 您必须从<img>标签中删除您的id="img1" ,因为您不能拥有多个具有相同ID的元素。

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. 如上所述,如果您对如何将事件处理程序附加到图像感到好奇,则无需通过javascript执行此操作。 You do need to change the checkbox id to something other than what the image id is. 您需要将复选框ID更改为图像ID以外的其他ID。 I renamed it to chk2 我把它改名为chk2

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

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

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

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

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