2011-02-04 9 views
5

मैं इस jQuery कोड है:क्लिक करें बाहर> छिपाने()

$(document).ready(function(){ 
//global vars 
var searchBoxes = $(".box"); 
var searchBox = $(".box"); 
var searchBoxDefault = "Search..."; 

searchBoxes.focus(function(e){ 
    $(this).addClass("active"); 
    $('#searchoptions').show(); 
}); 
searchBoxes.blur(function(e){ 
    $(this).removeClass("active"); 
}); 

searchBox.focus(function(){ 
    if($(this).attr("value") == searchBoxDefault) $(this).attr("value", ""); 
}); 
searchBox.blur(function(){ 
    if($(this).attr("value") == "") $(this).attr("value", searchBoxDefault); 
}); }); 

और html कोड:

<div id="search" class="right"> 
    <form method="post" class="clearfix"> 
    <input class="box left" type="text" value="Search..." /> 
    <input class="button right" type="submit" value="" /> 
    </form> 
    <div id="searchoptions"> 
    Options:<br /><input checked="checked" type="radio"> Option1</label> 
    <input type="radio"> Option2</label> 
    <input type="radio"> Option3</label> 
    </div> 
</div> 

सवाल यह है: जब मैं #search आईडी के बाहर क्लिक करें मैं कैसे कर सकते हैं, #searchoptions छुपाने के लिए?

मैं शरीर क्लिक के साथ कोशिश की, लेकिन कीड़े है ... और पूरी तरह से नहीं चलता है ...

उत्तर

7

बॉडी क्लिक पूरी तरह से काम करेगा। घटना प्रचार को रोकने के लिए केवल एक चीज है। यह काम करना चाहिए ...

$('body').click(function() { 
     $('#searchoptions').hide(); 
}); 

$('#searchoptions').click(function(event){ 
     event.stopPropagation(); 
}); 

@see http://api.jquery.com/event.stopPropagation/

4

ठीक है, के बाद से पृष्ठ पर कहीं एक click() प्रभावी रूप से $(searchbox).blur() ईवेंट हैंडलर फोन करेगा, तो आप सिर्फ कुछ जोड़ सकता है आपके प्रभाव को प्राप्त करने के लिए:

searchBox.blur(function(){ 
    if($(this).attr("value") == "") { 
     $(this).attr("value", searchBoxDefault); 
    } 

    $('#searchoptions').hide(); 

}); 

JS Fiddle demo

+0

काम नहीं करते ... जब मैं एक विकल्प चुनना चाहता हूं #searchoptions गायब हो जाता है ... –

0

आप क्या कर सकते दस्तावेज है कि लटकती छुपा देगा अगर लटकती बाहर कुछ क्लिक किया जाता है करने के लिए एक क्लिक करें घटना के लिए बाध्य है, लेकिन छिपा नहीं होगा यह अगर लटकती अंदर कुछ

searchBoxes.focus(function(e){ 
    $(this).addClass("active"); 
    $('#searchoptions').show(function(){ 

     $(document).bind('click', function (e) { 
      var clicked = $(e.target); 
      if (!clicked.parents().hasClass("class-of-dropdown-container")) { 
       $('#searchoptions').hide(); 
      } 
     }); 

    }); 
}); 

तो क्लिक किया जाता है जब यह छुपा, क्लिक करें घटना निकल

$(document).unbind('click'); 
संबंधित मुद्दे