在span标记上使用jquery if条件来显示隐藏div元素

时间:2017-06-07 16:31:42

标签: jquery if-statement onchange

我正在尝试以下脚本来检测span标记上的更改,然后显示或隐藏div元素。由于某种原因,if语句不起作用。我的浏览器中没有任何错误,也没有太多关于它可能出错的信息。

$('#ch1').on('change',function(){
if('#ch1' > 6) {

        $('#box1').hide(2000);
} else {
        $('#box1').show(2000); 
}

});

2 个答案:

答案 0 :(得分:1)

您可能想要检查元素值,因为您正在聆听change事件。

此外,jQuery具有toggle功能,使其更容易



$('#ch1').on('change', function() {
  $('#box1').toggle(this.value < 6);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ch1" value="2" />
<div id="box1" ">Less than six</div>
&#13;
&#13;
&#13;

作为一个FYI,span没有变化,您需要输入。

答案 1 :(得分:0)

At first, create a javascript ready function where you can put the span click code to show/hide div.

&#13;
&#13;
var temp = 1;
$(document).ready(function(){
   $("span").click(function(){   		
        if(temp == 1)    
        {
        	$('#tempdiv').hide(2000);
            temp = 2;
        }
        else
        {
        	$('#tempdiv').show(2000);
            temp = 1;
        }
    });
});
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

<span>If you click on me, then....</span>
<div id="tempdiv">This is a div that you can show and hide on span.</div>

</body>
</html>
&#13;
&#13;
&#13;