[英]How can I use getElementsByClassName with jQuery selector :not() selector
[英]How can I use the keyword $(this) in place of class selector - jQuery?
我在jQuery中有以下代码-
$(".new_makes_button").click(function(){
if($(".new_makes_button:checked").length == 0) {
那么,如何用$(this)替换上面代码第二行中的类选择器“ .new_makes_button”? 我只是在寻找正确的语法。 在这里,我有几个带有“ new_makes_button”类的复选框,然后单击其中的任何一个,我正在检查何时所有复选框都未选中,然后运行以下代码。
尝试这个:
if (!$(this).is(":checked")) {
...
}
您可以直接在单击的项目上查看选中的属性,如下所示:
if (!$(this).prop("checked")) {
// code here for when the item is not checked
}
一旦有了DOM元素(在this
元素中),就无需使用其他选择器,因为您可以直接检查该项目的属性。
这将检查当前项目是否被选中。 当前项目是事件源元素。 回调中的$(this)
是对单个元素的引用。
if(this.checked === false) {
}
但是,如果要查找是否.new_makes_button
选中.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());
});
如何用$(this)替换上面代码第二行中的类选择器“ .new_makes_button”?
如果您确实要使用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")));
在jQuery中,要作用的元素通常以此方式传递给jQuery函数的函数参数。 可以通过在函数参数中使用$(this)将其制成jQuery元素对象,例如:
$( 'new_makes_button')。点击(函数(){
$(this).animate({paddingLeft:$(this).width()},200);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.