Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 根据字符在多个输入上添加或删除类_Javascript_Jquery_Html - Fatal编程技术网

Javascript 根据字符在多个输入上添加或删除类

Javascript 根据字符在多个输入上添加或删除类,javascript,jquery,html,Javascript,Jquery,Html,我有10个输入字段,我想检查至少有2个字符在 <input type="text" /> <input type="text" /> <input type="text" /> $('input[type="text"]').on('keyup', function(){ if($(this).length > 2){ alert('yeah') } else { alert('no');

我有10个输入字段,我想检查至少有2个字符在

<input type="text" />
<input type="text" />
<input type="text" />

$('input[type="text"]').on('keyup', function(){ 
     if($(this).length > 2){
         alert('yeah')
     } else {
         alert('no');
     }
});

$('input[type=“text”]”)。在('keyup',function(){
如果($(此).length>2){
警惕(“是的”)
}否则{
警告(“否”);
}
});
我正在使用上述方法,但我一直收到“否”的警告

这是为什么?

$(这)
指的是jQuery对象,而不是元素的值。您需要首先通过
$.val()
方法获取值

这样做:

if ($(this).val().length > 2) { ... }

或者,正如@Taplar所建议的,您只需访问
this.value
属性(
this
将引用第一个匹配的元素)。通过这种方式,您可以稍微加快代码的速度,因为您不会创建新的jQuery对象实例

if (this.value.length > 2) { ... }
$(this)
指的是jQuery对象,而不是元素的值。您需要首先通过
$.val()
方法获取值

这样做:

if ($(this).val().length > 2) { ... }

或者,正如@Taplar所建议的,您只需访问
this.value
属性(
this
将引用第一个匹配的元素)。通过这种方式,您可以稍微加快代码的速度,因为您不会创建新的jQuery对象实例

if (this.value.length > 2) { ... }
$('input[type=“text”])。在('keyup',function(){
如果($(this.val().length>2){
console.log('yes')
}否则{
console.log('no');
}
});

$('input[type=“text”])。在('keyup',function(){
如果($(this.val().length>2){
console.log('yes')
}否则{
console.log('no');
}
});

我只想使用
这个.value
而不是创建一个不必要的jQuery对象。另外,使用
input
事件将仅在值发生变化时触发逻辑,而不会触发其他键,如箭头键和其他实际上没有改变值的键

$('input[type=“text”])。在('input',function(){
log(this.value.trim().length>2?'yeah':'no');
});

我只想使用
这个.value
而不是创建一个不必要的jQuery对象。另外,使用
input
事件将仅在值发生变化时触发逻辑,而不会触发其他键,如箭头键和其他实际上没有改变值的键

$('input[type=“text”])。在('input',function(){
log(this.value.trim().length>2?'yeah':'no');
});


非常感谢!如果我想使用else删除一个类,那么我如何定位$(this)?
$(this)。removeClass('class-name')
True,添加了一个关于这个的注释。非常感谢!如果我想使用else删除一个类,那么如何将$(this)作为目标呢?
$(this).removeClass('class-name')
True,添加了一个关于这一点的注释。