HTML 复选框 onclick 在 Javascript 中调用
我在尝试弄清楚如何使我的代码的某个部分正常工作时遇到了一些麻烦。
<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All" onclick="selectAll(document.wizard_form, this);">
<label for="check_all_1" onclick="toggleCheckbox('check_all_1'); return false;">Select All</label>
这是我的 HTML,它可以正常工作(单击文本将单击该框)。它的 javascript 非常简单:
function toggleCheckbox(id) {
document.getElementById(id).checked = !document.getElementById(id).checked;
}
但是,当标签使复选框被单击时,我希望输入发生 onclick。目前 onClick js 还没有运行。关于如何做到这一点的建议是什么? 我尝试将输入的 onclick 添加到标签的 onclick,但这不起作用。
任何建议/解决方案都会很棒。
I am having a bit of trouble trying to figure out how to get a certain part of my code to work.
<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All" onclick="selectAll(document.wizard_form, this);">
<label for="check_all_1" onclick="toggleCheckbox('check_all_1'); return false;">Select All</label>
This is my HTML which works as it should (clicking the text will click the box). The javascript for it is pretty simple:
function toggleCheckbox(id) {
document.getElementById(id).checked = !document.getElementById(id).checked;
}
However I want the onclick to happen for the input when the label is what makes the checkbox to be clicked. At this current time the onClick js does not go. What is one suggestion on how to do this?
I tried to add the onclick of the input to the onclick of the label but that doesn't work.
Any suggestions/solutions would be wonderful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如何将
复选框
放入标签
中,使标签自动为复选框“点击敏感”,并为复选框指定一个onchange
事件?这还会捕获用户使用键盘来切换复选框,而
onclick
则不会。How about putting the
checkbox
into thelabel
, making the label automatically "click sensitive" for the check box, and giving the checkbox aonchange
event?This will additionally catch users using a keyboard to toggle the check box, something
onclick
would not.没有 onclick 的标签将按照您的预期运行。它改变了输入。您真正想要的是在单击标签时执行
selectAll()
,对吗?然后只将select all添加到onclick标签上。或者将输入包装到标签中并仅为标签分配 onclick
Label without an onclick will behave as you would expect. It changes the input. What you relly want is to execute
selectAll()
when you click on a label, right?Then only add select all to the label onclick. Or wrap the input into the the label and assign onclick only for the label
jQuery 有一个函数可以做到这一点:
在你的头脑中包含以下脚本:
(或者只是在线下载 jQuery.js 文件并将其包含在本地)
使用此单击输入时切换复选框的脚本:
如果我理解您想要执行的操作,那么应该可以执行您想要的操作。
jQuery has a function that can do this:
include the following script in your head:
(or just download the jQuery.js file online and include it locally)
use this script to toggle the check box when the input is clicked:
That should do what you want if I understood what you were trying to do.
您还可以从 HTML 中提取事件代码,如下所示:
You can also extract the event code from the HTML, like this :