2017-06-07 85 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>