2012-10-05 137 views
0

我基本上有2個事件。最上面的一個從jQuery自動完成中選擇選項並將其輸出到div searchresultdata。第二個需要從#* SEARCH_INPUT *的內容,並輸出到searchresultdata我可以結合這些事件嗎?

var devices = [ 
    "ActionScript", 
    "AppleScript", 
    "Asp", 
    "BASIC", 
    "C", 
    "C++", 
    "Clojure", 
    "COBOL", 
    "ColdFusion", 
    "Erlang", 
    "Fortran", 
    "Groovy", 
    "Haskell", 
    "Java", 
    "JavaScript", 
    "Lisp", 
    "Perl", 
    "PHP", 
    "Python", 
    "Ruby", 
    "Scala", 
    "Scheme" 
    ]; 

$("#search_input").autocomplete({ 
    source: devices, 
    select: function(e, i) { 

     var search_input = i.item.value; 
     document.getElementById('searchresultdata').innerHTML = search_input; 
    } 
}); 

//Append div with contents from function sendSelected 
$("#search_input").on("keyup change", function() { 
    var search_input = $(this).val(); 
    if (search_input.length > 1 || search_input == '*') { 
     document.getElementById('searchresultdata').innerHTML = "Everything"; 
    } 

    document.getElementById('searchresultdata').innerHTML = search_input; 
}); 

對於一個活生生的例子,請參閱: http://jsfiddle.net/k2SMb/4/

反正我有可以合併成一個這使它成爲一個比較整潔?

回答

1

你可以通過將兩個事件鏈接在一起來使它更整潔,然後你可以使用jQuery的$('#id_selector'),並且當你只需要一次時就不用寫變量。結果:

$("#search_input").autocomplete({ 
    source: devices, 
    select: function(e, i) { 
     $('#searchresultdata').text(i.item.value); 
    } 
}).on("keyup change", function() { 
    var search_input = $(this).val(); 
    if (search_input.length > 1 || search_input == '*') { 
     $('#searchresultdata').text("Everything") 
    } 
    $('#searchresultdata').text(search_input); 
});​ 
相關問題