Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 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 Answer

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());
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...