我在jQuery中有以下代码-
$(".new_makes_button").click(function(){
if($(".new_makes_button:checked").length == 0) {那么,如何用$(this)替换上述代码第二行中的类选择器".new_makes_button“?我只是在寻找正确的语法。这里有几个带有"new_makes_button“类的复选框,并单击其中任何一个,我正在检查所有复选框何时未选中,然后运行以下代码。
发布于 2014-07-13 18:15:24
这将检查当前项目是否被选中。当前项是事件源元素。回调内部的$(this)是对单个元素的引用。
if(this.checked === false) {
}但是,如果您想知道是否没有选中任何带有.new_makes_button的元素,那么您可以使用jQuery。
$(".new_makes_button").click(function() {
// $(this) at this point is a reference to a
// single element. To get Them all you may do this:
var total = 0;
$(".new_makes_button").each(function(index, element) {
if(this.checked === true) {
total++;
}
});
alert("Total checked item" + (total).toString());
});示例
如何将上述代码的第二行中的类选择器".new_makes_button“替换为$(this)?
但是,如果您真的想使用this对象,那么不使用$(this)是不正确的语法。
要在该方法中使用this并让它引用一个.new_makes_button元素数组,可以使用bind更改它的值。在本例中,this将引用一个jQuery对象。
$(".new_makes_button").click(function(e) {
// here `this` is a jquery object!
// no need to call the `$`
console.log(this.length);
}.bind($(".new_makes_button")));示例
最短可能解
$(".new_makes_button").click(function(e) {
if(this.filter(':checked').length == 0) {
// handle condition
}
}.bind($(".new_makes_button")));发布于 2014-07-13 18:08:28
试试这个:
if (!$(this).is(":checked")) {
...
}发布于 2014-07-13 18:12:51
您可以直接查看单击的项上的选中属性,如下所示:
if (!$(this).prop("checked")) {
// code here for when the item is not checked
}一旦您有了DOM元素(在this中有),就没有必要使用进一步的选择器了,因为您可以直接检查该项的属性。
https://stackoverflow.com/questions/24725687
复制相似问题