用户标记复选框时触发jquery动作 [英] Triggering a jquery action when the users mark a Checkbox
问题描述
im在javascript和jquery中非常新.我有这个复选框:
im very new in javascript and jquery. I have this checkbox:
<label for="editable">Editable </label><input name="editable" type="checkbox" id="edita"/>
这个jquery动作:
And this jquery action:
$('#slickbox1').toggle(400);
return false;
我想在选中复选框时执行该操作.谢谢!
I want to execute that action when the checkbox is checked. Thanks!
推荐答案
您可以尝试:
$('#edita').change(
function() {
if ($(this).is(':checked')) {
$('#slickbox1').toggle(400);
}
});
尽管值得注意的是,仅在选中toggle()
方法时运行该方法(假定它未经检查就开始运行)涉及到用户单击输入一次来显示它,然后再次输入删除该检查并再次 对其进行重新检查,以便由于toggle()
而隐藏.
Although it's worth noting that running the toggle()
method only when it's checked (assuming that it starts off un-checked) involves the user clicking the input once to show it, and then again to remove the check and again to re-check it so that it hides as a result of the toggle()
.
可能值得考虑:
$('#edita').change(
function() {
if ($(this).is(':checked')) {
// checked
$('#slickbox1').show(400);
}
else {
// un-checked
$('#slickbox1').hide(400);
}
});
如果选中该复选框,则显示 $('#slickbox1')
,如果未选中,则将其隐藏
Which shows $('#slickbox1')
if the check-box is checked, and hides it if not,
或:
$('#edita').change(
function() {
$('#slickbox1').toggle(400);
});
选中和取消选中input
时,会在show()
和hide()
之间切换$('#slickbox1')
.
Which toggles the $('#slickbox1')
between show()
and hide()
when the input
is checked and un-checked.
已编辑,以解决DomingoSL(OP)在评论中提出的问题:
Edited to address the question raised by DomingoSL (the OP) in comments:
...如果现在触发不是一个复选框而是一个按钮,您可以进行编辑以查看过程吗?
...can you please make an edit to see the procedure if now the triger is not a checkbox but a button?
需要对此进行两项更改:
There are two changes that need to be made to accommodate this:
- a
button
没有change
事件,因此它必须使用click()
相反,并且 - 一个
button
没有:checked
(或等效状态)状态,因此if
/else
变得多余.
- a
button
has nochange
event, so it would have to useclick()
instead, and - a
button
has no:checked
(or equivalent) state, so theif
/else
becomes redundant.
但是,我假设您的元素名称保持不变,因为您没有发布相反的信息,这是一种实现方法,
One way of doing it, though, and I'm assuming your element names remain the same since you've posted no information to the contrary, is:
$('#edita').click(
function(){
$('#slickbox1').toggle(400);
});
这篇关于用户标记复选框时触发jquery动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!