2012-08-23 34 views
0

我有一個代碼,該函數是autosuggestion。這段代碼很好用。我只想問你如何在文本框中輸入文本後關閉框。在我的代碼中,當我嘗試點擊任何地方時,它沒有關閉框。所以我想要做的是當我點擊任何地方,所以箱子必須關閉。如何在任何地方點擊時關閉盒子?

這裏是我的jQuery:

$(document).ready(function() { 
    $(".text_search").keyup(function() { 
     var searchbox = $(this).val(); 
     var dataString = 'searchword=' + searchbox; 
     if (searchbox == '') {} else { 
      $.ajax({ 
       type: "POST", 
       url: "search1.php", 
       data: dataString, 
       cache: false, 
       success: function(html) { 
        $("#display").html(html).show(); 
       } 
      }); 
     } 
     return false; 
    }); 
});​ 

HTML:

<div class="search"> 
<form method="get" action="search.php" autocomplete="off"> 
<input class="text_search" type="text" name="q" id="q" value="Search people" onfocus="if (this.value == 'Search people') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search people';}"> 
</form> 
</div> 

<div id="display"> 
</div> 

回答

4

只是在文檔正文中添加一個事件處理程序,並關閉對話框,如果它是開放的。把,在你的身體的末尾:

<script> 
    $(window).ready(function(){ 
     $('body').click(function(){ 
      $("#display").hide(); 
     }); 
    }); 
</script> 

編輯:

如果你想也有搜索再次推出當您單擊搜索框,改變你的腳本是:

$(document).ready(function() { 
    var launchSearch = function() { 
     var searchbox = $(this).val(); 
     var dataString = 'searchword=' + searchbox; 
     if (searchbox == '') {} else { 
      $.ajax({ 
       type: "POST", 
       url: "search1.php", 
       data: dataString, 
       cache: false, 
       success: function(html) { 
        $("#display").html(html).show(); 
       } 
      }); 
     } 
     return false; 
    }; 
    $(".text_search").keyup(launchSearch).click(launchSearch); 
    $('body').click(function(){ 
     $("#display").hide(); 
    }); 
});​ 
+0

對不起,我怎麼可以結合使用我的JS?我試過了,但現在正在工作。 –

+0

@ X-men:確定你把它放在'$(document).ready();'中。 – Purag

+0

謝謝。現在已經有效了。還有一個問題:如果我嘗試再次單擊文本輸入,是否可以繼續搜索?例如:我嘗試搜索文本:'da',然後離開文本框並再次點擊文本框。 –

3

試試這個:

$('body').click(function(){ 
     $("#display").hide(); 
    }); 
+0

如果我在#display裏面點擊,它也會關閉。 – neworld

1
$(document).click(function(e) { 
        if($(e.target).parents("#display").length == 0 && 
        $(e.target).attr("id") != "display") { 
         $("#display").hide(); 
        } 
       }); 

您必須檢查是否點擊不在顯示DIV

0

試試這個

$(document).ready(function(){ 
$('body').click(function(){ 
      $("#display").hide(); 
     }); 

$(".text_search").keyup(function() 
{ 
var searchbox = $(this).val(); 
var dataString = 'searchword='+ searchbox; 
if(searchbox=='') 
{} 
else 
{ 
$.ajax({ 
type: "POST", 
url: "search1.php", 
data: dataString, 
cache: false, 
success: function(html) 
{ 
$("#display").html(html).show(); 
} 
}); 
}return false; 
}); 
}); 
相關問題