JQuery不为null而css没有woking

时间:2017-01-09 07:52:02

标签: jquery html css

我想在输入字段有一些值时在css中应用这些jquery, 我尝试了这些jquery代码,但它无效。

请建议我!

if ($('#user-email').val() != ''){
    $(".email-capt").css({"position":"absolute","margin-top":"0px"});
}
<div class="input-container input-email">
     <button class="btn btn-default email-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
     <input type="email" required="" value="" tabindex="1" name="name" class="" id="user-email">
     <label for="arrival" class="email-capt">Enter your email to be in the know</label>
</div>

3 个答案:

答案 0 :(得分:1)

您需要检查input字段的值何时发生变化。目前,您正在检查DOM加载的时间。

尝试这一点,而不是:

$("#user-email").change(function(){ // on input value change  
    if($.trim($(this).val()) != ''){
        $(".email-capt").css({"position":"absolute", "margin-top":"0px"});
    }
});

如果您想查看点击button的时间,可以执行以下操作:

$(".email-btn").click(function(){ // if button is clicked
    if($.trim($(this).val()) != ''){
        $(".email-capt").css({"position":"absolute", "margin-top":"0px"});
    }
});

答案 1 :(得分:1)

&#13;
&#13;
function checkFilled() {
    var inputVal = document.getElementById("subEmail");
    if (inputVal.value == "") {
        inputVal.style.backgroundColor = "yellow";
    }
    else{
        inputVal.style.backgroundColor = "green";
    }
}

checkFilled();
&#13;
<input type="text" id="subEmail" onchange="checkFilled();">
&#13;
&#13;
&#13;

答案 2 :(得分:0)

&#13;
&#13;
$('button').click(function() {
  if ($('#user-email').val() != ''){
    $(".email-capt").css({"display":"block","color":"red"});
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="input-container input-email">
     <button class="btn btn-default email-btn">Click</button>
     <input type="email" required tabindex="1" name="name" id="user-email">
     <label for="arrival" class="email-capt" style="display:none;">Enter your email to be in the know</label>
</div>
&#13;
&#13;
&#13;

问题在于,js代码仅在加载页面时运行一次。
您需要定义代码运行按钮的onClick。为此使用 - $('button').click(function() {...});