[英]jQuery blur function not working
I am using html and jQuery library, trying to avoid core JavaScript, just bc I do not want to mix it 我正在使用html和jQuery库,试图避免使用核心JavaScript,只是bc我不想将其混合使用
I have 3 fields, when user click on field1, then click some where else, I want field1 border to turn red only. 我有3个字段,当用户单击field1时,然后在其他地方单击时,我希望field1边框仅变为红色。
If user click on field2 then clicks some where else, I want field2 border to turn red only. 如果用户单击field2,然后单击其他位置,则我希望field2边框仅变为红色。
Right now blur()
works perfectly but it creates a red border on every fields. 现在
blur()
可以正常工作,但是在每个字段上都创建了一个红色边框。 this is because I am using .input class. 这是因为我正在使用.input类。 any idea how can I do this without getting id?
任何想法,我怎么能做到这一点而没有身份证? bc I will have 40 fields when i am done
公元前完成后,我将有40个字段
html code: html代码:
<asp:TextBox runat="server" id="test1" class="input green" /> <br />
<asp:TextBox runat="server" id="test2" class="input blue" />
jquery code: jQuery代码:
$(function() {
$(".input").blur(function() {
if ($(".input").val().trim() == '')
$(".input").css('border-color', 'red');
else
$(".input").css('border-color', '');
});
});
Use $(this)
instead of repeating class name. 使用
$(this)
而不是重复类名。
$(function() { $(".input").blur(function() { if ($(this).val().trim() == '') $(this).css('border-color', 'red'); else $(this).css('border-color', ''); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="input"/> <input type="text" class="input"/> <input type="text" class="input"/>
Optional 可选的
Also instead of $(this).val().trim() == ''
you can use $(this).val().length <= 0
也可以代替
$(this).val().trim() == ''
使用$(this).val().length <= 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.