2017-06-07 39 views
0

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

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

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

});

回答

1

您可能想检查元素值,看到您正在监听change事件。

此外,jQuery有一个toggle功能,使这更容易一点

$('#ch1').on('change', function() { 
 
    $('#box1').toggle(this.value < 6); 
 
});
<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>

作为一个仅供参考,一个span不会改变,你需要的输入。

0

var temp = 1; 
 
$(document).ready(function(){ 
 
    $("span").click(function(){ \t \t 
 
     if(temp == 1)  
 
     { 
 
     \t $('#tempdiv').hide(2000); 
 
      temp = 2; 
 
     } 
 
     else 
 
     { 
 
     \t $('#tempdiv').show(2000); 
 
      temp = 1; 
 
     } 
 
    }); 
 
});
<!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>