使用 jQuery 选中复选框时如何执行操作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1854156/
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
How to do an action when a checkbox is checked with jQuery?
提问by Keith Donegan
I want to do an action when a user checks a checkbox, but I can't get it to work, what am I doing wrong?
我想在用户选中复选框时执行一个操作,但我无法让它工作,我做错了什么?
So basically, a user goes to my page, ticks the box, then the alert pops up.
所以基本上,用户转到我的页面,勾选框,然后弹出警报。
if($("#home").is(":checked"))
{
alert('');
}
回答by Joel
What you are looking for is called an Event. JQuery provides simple event binding methods like so
您要查找的内容称为事件。JQuery 提供了像这样简单的事件绑定方法
$("#home").click(function() {
// this function will get executed every time the #home element is clicked (or tab-spacebar changed)
if($(this).is(":checked")) // "this" refers to the element that fired the event
{
alert('home is checked');
}
});
回答by Zoltan
Actually the change()
function is much better for this solution because it works for javascript generated actions, such as selecting every checkbox via a script.
实际上change()
,此解决方案的功能要好得多,因为它适用于 javascript 生成的操作,例如通过脚本选择每个复选框。
$('#home').change(function() {
if ($(this).is(':checked')) {
...
} else {
...
}
});
回答by Jeff Martin
you need to use the .click event described here: http://docs.jquery.com/Events/click#fn
您需要使用此处描述的 .click 事件:http: //docs.jquery.com/Events/click#fn
so
所以
$("#home").click( function () {
if($("#home").is(":checked"))
{
alert('');
}
});
回答by Jeff Martin
$("#home").click(function() {
var checked=this.checked;
if(checked==true)
{
// Stuff here
}
else
{
//stuff here
}
});
回答by Chaudhary
$( "#home" ).change(function() {
if(this.checked){
alert("The Check-box is Checked"); // Your Code...
}else{
alert("The Check-box is Un-Checked"); // Your Code...
}
});
回答by Bassem Shahin
for some cases, when you have a dynamic content you can use this code:
在某些情况下,当您有动态内容时,您可以使用以下代码:
$(function() {
$(document).on('click','#home',function (e) {
if($(this).is(":checked")){
alert('Home is checked')
}else{
alert('Home is unchecked')
}
});
});