Jquery $(这个)不起作用

0 css jquery input this

我有这个代码

    if($('input[type="text"]').val() == ''){
        $(this).css('width', '20%');
        }
Run Code Online (Sandbox Code Playgroud)

HTML

<input id="id_nombre" maxlength="100" name="nombre" placeholder="Inserte su nombre" type="text">
<input id="id_email" maxlength="150" name="email" placeholder="Inserte su E-Mail" type="text">
Run Code Online (Sandbox Code Playgroud)

这不起作用,但如果我写输入而不是它,它的工作原理.似乎这是指向整个HTML

And*_*old 5

$(this)指的是函数最外层范围的调用者,它可能是你的文档或其他容器(没有上下文很难说).一个if块虽然是each遗嘱,但不会改变这一点.

如果要防止重复,请随意将jQuery对象分配给变量:

var input = $('input[type="text"]');
if (input.val() == '') {
    input.css('width', '20%');
}
Run Code Online (Sandbox Code Playgroud)

编辑:由于您有多个输入,您将通过使用each循环获得所需的行为:

$('input[type="text"]').each(function() {
    if ($(this).val() == '') {
        $(this).css('width', '20%');
    }
});
Run Code Online (Sandbox Code Playgroud)