Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

How to activate Onblur only if two divs are out of focus JQUERY:Javascript

For an autosuggest

i have one div for the input tag and another for the suggestions div...i want the suggestions div to disappear after either

1) an element is selected in the suggestions div

or

2) when an area outside the two divs is clicked

The question is where to add an "onblur" event right now i have

<input type = "text" name= "target" value = "" id="target" style="width:150px" onblur ="setTimeout('removeSuggestions()', 20);" onkeyup ="getSuggestions(this.value);"/>

<div id ="suggestions"></div>

and

function getSuggestions(value){
   if (value !=""){
   $.post("target.php", {targPart:value}, function(data) {
     $("#suggestions").html(data);
    if(value.length>2){
        doCSS();
        }

   });
   } else {
    removeSuggestions();
    }

  }

   function removeSuggestions(){

   $("#suggestions").html("");
   undoCSS();
   }
  function addText(value){

      $("#target").val(value);

  }
  function doCSS(){
  $("#suggestions").css({
      'border' : 'solid',
       'border-width': '1px'

    });

  }

  function undoCSS(){
   $("#suggestions").css({
      'border' : '',
       'border-width': ''

    });
  }

But everytime I try to click a suggestion the suggestions div goes away because once i go out of the input field remove suggestions is called. The timeout is supposed to help but isn't. How can i fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Perhaps something like this will solve your problem. We only need to monitor the blur of search box because clicking out of it (even on suggestions) will trigger the hide event.

http://jsfiddle.net/9Yt9L/3/

$('#search').focus(function() {
    $('#suggestions').slideDown();
});

$('#search').blur(function() {
    $('#suggestions').slideUp();
});

$('#suggestions div').click( function() {
    $('#search').val($(this).html());
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...