本文介绍了在输入中添加类(如果值没有改变,则删除)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了这个简单的js将类添加到焦点上的输入中,并在失去焦点时将其删除(如果值为空)。但是,无论值是否为空,该类都不会被删除。感谢您的任何帮助,非常感谢

HTML: code>< form id =prospects_formmethod =postaction =...>
< input id =form_nametype =textname =nameplaceholder =Name */>
< input id =form_emailtype =textname =emailplaceholder =Email */>
< input id =form_subjecttype =textname =subjectplaceholder =Subject *maxlength =50/>
< textarea id =form_messagerows =6cols =5name =messageplaceholder =Message *maxlength =500>< / textarea>

< button id =form_sendclass =btn btn_whitetype =submit>发送< / button>
< / form>

JS:

  //当输入焦点时
$('#prospects_form> *')。focus(function(){
$(this).addClass( hasText);
}); ($(this).val ===''){$(this).removeClass(hasText)
$('#prospects_form> *')。blur(function(){
if );}
});


解决方案

您可以使用 attr removeAttr

  //当输入被关注时
$('#prospects_form> *')。focus(function() {
$(this).attr('class','hasText');
}); ($(this).val()=='')。 {
$(this).removeAttr('class','hasText');
}
});

错误在于,您错过了()模糊事件中的 val 的前面。这是错误,并导致错误,你也可以在控制台中看到。



这也是一个小提琴:)
$ b $祝你好运!


I've written this simple js to add class to an input on focus, and remove it when it loses focus (if value is empty). However the class doesn't get removed regardless of whether the value is empty or not. Thanks for any help, hugely appreciated

HTML:

<form id="prospects_form" method="post" action="...">
    <input id="form_name" type="text" name="name" placeholder="Name*" />
    <input id="form_email" type="text" name="email" placeholder="Email*" />
    <input id="form_subject" type="text" name="subject" placeholder="Subject*" maxlength="50" />
    <textarea id="form_message" rows="6" cols="5" name="message" placeholder="Message*" maxlength="500"></textarea>

    <button id="form_send" class="btn btn_white" type="submit">Send</button>
</form>

JS:

// When input is focussed
$('#prospects_form > *').focus(function() {
    $(this).addClass("hasText");
});
$('#prospects_form > *').blur(function() {
    if ($(this).val === '') { $(this).removeClass("hasText"); }
});
解决方案

You can use attr and removeAttr too.

// When input is focussed
$('#prospects_form > *').focus(function() {
 $(this).attr('class', 'hasText');
});
// blur event..
$('#prospects_form > *').blur(function() {
 if ($(this).val() == '') {
   $(this).removeAttr('class', 'hasText');
 }
});

The error was, you were missing () infront of val in the blur event. Which was the error, and was causing an error and you would have seen that in the Console too.

Here is a fiddle for that too :) http://jsfiddle.net/afzaal_ahmad_zeeshan/kdd84/1/

Good luck!

这篇关于在输入中添加类(如果值没有改变,则删除)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:23