我在jQuery中有以下代码 -
$(".new_makes_button").click(function(){
if($(".new_makes_button:checked").length == 0) {
那么如何用$(this)替换上面代码第二行中的类选择器“.new_makes_button”?我只是在寻找正确的语法。在这里,我有几个带有“new_makes_button”类的复选框并单击其中任何一个,我正在检查何时取消选中所有复选框,然后运行以下代码。
答案 0 :(得分:3)
试试这个:
if (!$(this).is(":checked")) {
...
}
答案 1 :(得分:1)
您可以直接在点击的项目上查看checked属性,如下所示:
if (!$(this).prop("checked")) {
// code here for when the item is not checked
}
一旦你拥有了DOM元素(你在this
中),就不需要使用其他选择器了,因为你可以直接检查该项的属性。
答案 2 :(得分:1)
这将检查当前项目是否已被选中。当前项是Event source元素。回调中的$(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")));
答案 3 :(得分:0)
在jQuery中,被执行的元素通常会传递给jQuery函数的函数参数。它可以通过在函数参数中使用$(this)来制作成jQuery元素对象, 例如:
$(' .new_makes_button&#39)。单击(函数(){
$(this).animate({paddingLeft:$(this).width()},200);
});