大家好,
想請教一下,
下面這個範例的第一個 textarea 使用 Autocomplete 可以成功,
但如果透過按紐再顯示出來的第二個 textarea 使用 Autocomplete 為什麼無法成功呢?
請問應該如何修改才能讓第二種方式也可以成功使用 Autocomplete?
謝謝
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Multiple values</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#tags" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
function clickme(){
var result = "<textarea id='tags'></textarea>";
document.getElementById('all').innerHTML = result;
}
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tag programming languages: </label>
<br>
<textarea id="tags"></textarea>
<br>
<button onclick="clickme()">Click me</button>
<p id="all"></p>
</div>
</body>
</html>
請記得一個重點。
永遠都不要認為javascript可以重覆id。地雷會炸死你。
如果可以的話,請不要再用id來當取元件的依據了
最後,元件是可以自定義屬性的。它是可以重覆地!!
但雖然說可以重覆。也要懂得jquery取元件的依據原理是什麼。
要不然,雷會炸死你。