javascript JQUERY ON('change') 获取复选框值和状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27758168/
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
JQUERY ON('change') get checkbox value and state
提问by The One
How can I "get" the checkbox that changed inside div "containerDIV"?
如何“获取”在 div“containerDIV”中更改的复选框?
View:
看法:
@model MyModel
<div id="containerDIV">
<ul id="CheckBoxList">
@foreach (XObject t in MyModel.XCollection)
{
<li>
<input type="checkbox" value="@t.id"/>
</li>
}
</ul>
On the JavaScript (Jquery) side, I have this:
在 JavaScript (Jquery) 方面,我有这个:
$('#containerDIV').on('change', '#CheckBoxList', function (event) {
var id = $(this).val(); // this gives me null
if (id != null) {
//do other things
}
});
It's clear that $this
is not the checkbox, it's the div containerDIV
or checkBoxList
很明显,这$this
不是复选框,而是 divcontainerDIV
或checkBoxList
How can I get to the checkbox's state and value?
如何获得复选框的状态和值?
回答by jmore009
If your input
is not being created dynamically after the DOM loads you can just call:
如果您input
在 DOM 加载后不是动态创建的,您可以调用:
$('#CheckBoxList input[type=checkbox]').change(function() {
var id = $(this).val(); // this gives me null
if (id != null) {
//do other things
}
});
or to use .on()
you just need to target the input
that's getting clicked:
或者使用.on()
你只需要定位input
被点击的对象:
$('#CheckBoxList').on('change', 'input[type=checkbox]', function() {
var id = $(this).val(); // this gives me null
if (id != null) {
//do other things
}
});
回答by DripDrop
If you can, add the events as an attribute, like onchange='function(this);'
. This returns the element to the function, so you can get data such as it's ID, or just modify it like that.
如果可以,请将事件添加为属性,例如onchange='function(this);'
. 这会将元素返回给函数,因此您可以获取诸如 ID 之类的数据,或者只是像这样修改它。
Good Luck!
祝你好运!
回答by The One
Following billyonecan comment, this is another way to do it:
在 billyonecan 评论之后,这是另一种方法:
$('#containerDIV').on('change', '#CheckBoxList', function (event) {
var id =$(event.target).val();
if (id != null) {
//do other things
}
});