Jquery - Click outside and Hide Div

这一生的挚爱 提交于 2019-12-25 13:18:23

问题


I am using this: http://www.useful-dates.com/search/

How should the script be written to say, 1. When the user clicks the input, the scrolled div is shown. 2. When the user click outside of the scrolled div, the scrolled div hides.

Like this, but i have had no luck re-writting the script: http://rob-bell.net/static/ddlist.html

Iv searched and tried all kinds of things on the net and no luck, please help?


回答1:


The easiest way of doing this is when your script is triggered to display the list (the scrolled div) it creates a trigger to the click event on the document itself aswell. Something like this:

$("selector to your div").click(function() {
    var scrolledDiv = $("selector to your scrolled div");
    scrolledDiv.show();
    $(document).one(function() {
        scrolledDiv.hide();
    });
});

By using the one() the code to hide the scroll list will only be executed once, so it wont run each time the user is clicking the document. But remember that it will also trigger on clicks inside your scrolling div, if you dont want that stop the propagation of the click event like this:

$("selector to your scrolled div").click(function(e) {
    e.stopPropagation();
});



回答2:


If you look at the source code of your example ;

            $(document).click(function(){

                $('.ddcontainer > div > ol').hide();

            });

This hides the div when there has been a click on the document.

Give you div an ID like so:

<div id="searchResults" style="height:95px;width:290px;overflow:scroll;overflow-x:hidden;margin: 2px 0 0 0;">

and then:

$(document).click(function(){

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

});

Alternatively and maybe a better solution is to use focus and blur:

$("#kwd_search").focus(function(){
    $('#searchResults').show();
}).blur(function(){
    $('#searchResults').hide();
});

This will show the results when the focus is put onto the input, and removes it when you 'leave' the input.

UPDATE

With the autocomplete plugin, you can perform a task after the item has been selected like this:

$( "#tags" ).autocomplete({
    source: availableTags
}).bind( "autocompleteselect", function(event, ui) {
    location.href = ui.item.value; // If the value of the item is a url, this will forward you to it
});


来源:https://stackoverflow.com/questions/9240869/jquery-click-outside-and-hide-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!