2017-02-23 69 views
0

我每時每刻都在苦苦掙扎,今天再一次。 我附加了新的文本元素,我想將自動完成綁定到它。動態元素上的自動完成

這個代碼在功能上與以前的onClick

$('#highlights').before("<input type='text' id='check_name' name='name' placeholder='Name of OPM' required class='ui-autocomplete-input'>"); 

這是自動完成網頁上的結束

<script type="text/javascript"> 
$("#check_name").autocomplete({ 
     source: "src/check_name.php", 
     minLength: 1 
    }); 
</script> 

PHP文件的工作很好,當我通過URL訪問它。

+0

可能重複: jQuery自動完成動態創建的輸入](http://stackoverflow.com/questions/2663573/jquery-autocomplete-for-dynamically-created-inputs) –

+0

也許是這樣,但我已經檢查了答案,它並沒有幫助我。那傢伙在那裏有不同的代碼。 –

回答

1

因爲.before():在匹配元素集中的每個元素之前插入由參數指定的內容。

您可以使用.prev()

的片段:

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

 

 
    $('#highlights').before("<input type='text' id='check_name' name='name' placeholder='Name of OPM' required class='ui-autocomplete-input'>") 
 
     .prev("#check_name") // get the newly prev added ele 
 
     .autocomplete({ 
 
      source: availableTags, 
 
      minLength: 1 
 
     });
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/> 
 
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> 
 
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> 
 

 

 
<div id="highlights"></div>

+1

謝謝:)工作 –

1

試試這個方法來處理動態控制,

var $addedInput=$("<input type='text' id='check_name' name='name' placeholder='Name of OPM' required class='ui-autocomplete-input'>"); 
$('#highlights').before($addedInput); 
$addedInput.autocomplete({ 
    source: "src/check_name.php", 
    minLength: 1 
}); 
+1

謝謝:)工作 –