输入字段为空时显示/隐藏div(jquery,javascript)

我有一个带内容的div ,默认隐藏,我想在用户输入时在#control的输入字段中显示它。

 
//some content here........

 // Bind keyup event on the input $('#control').keyup(function() { // If value is not empty if ($(this).val().length == 0) { // Hide the element $('.show_hide').hide(); } else { // Otherwise show it $('.show_hide').show(); } }).keyup(); // Trigger the keyup event, thus running the handler on page load 
  
//some content here........

使用#control附加input事件,如下所示: –

 $('#control').on('input', function(){ if($.trim(this.value) != "") $(this).next('div.show_hide').show(); else $(this).next('div.show_hide').hide(); }); 

更短版本: –

 $('#control').on('input', function(){ $(this).next('div.show_hide').toggle($.trim(this.value) != ""); }); 

要么

 $('#control').on('input', function() { $(this).next('div.show_hide').toggle(this.value.length > 0); }); 

或者(在评论中添加@Rayon回答)

 $('#control').on('input', function(){ $(this).next('div.show_hide').toggle(!this.value); });