2016-07-07 87 views
0

我做了一些jquery验证,并且当用户离开input并且没有写入内容时,我想要一些文本显示为placeholder占位符没有显示

我写了这个代码

$('input[type="text"]').on('blur', function() { 
    if (!!$(this).val()) { 
     $(this).css({ 
      'border': '#ff8383 1px solid' 
     }); 
     $(this).attr('placeholder', 'this field is required'); 
    } 
    else { 
     $(this).css({ 
      'border': '#c3c3c3 1px solid' 
     }); 
     $(this).attr('placeholder', ''); 
    } 
}); 

它可以在Chrome浏览器开发工具 chrome dev tool,但它不`吨显示在页面上。

回答

1

你有一个额外!这里:

!!$(this).val() 

,您可以在同一(this)

$('input[type="text"]').on('blur', function() { 
 
    if (!$(this).val()) { 
 
    $(this).css({ 
 
     'border': '#ff8383 1px solid' 
 
    }).attr('placeholder', 'this field is required'); 
 
    } else { 
 
    $(this).css({ 
 
     'border': '#c3c3c3 1px solid' 
 
    }).attr('placeholder', ''); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input type="text" placeholder="test" /> 
 
<input type="text" placeholder="" /> 
 
<input type="text" />

+0

加入cssattr起初,我写了一个“! “,但是如果声明不起作用。这是因为我的价值=“”在我的HTML。你给了我一个线索。 –

+0

我现在更新了答案,如果你想看看 – dippas

1

这可能是问题; if语句中有2个爆炸声。

if (!!$(this).val()) {