2

美好的一天。谷歌地方動態輸入自動完成

我想補充谷歌地方自動填充使用下面的代碼動態創建輸入:

<html> 
<head> 
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script> 
<script type="text/javascript"> 
var _autoComplCounter = 0; 

function assignAutoCompl(_id) 
{ 
    var _autocomplete = new google.maps.places.Autocomplete(document.getElementById(_id)); 
    _autocomplete.setTypes(['geocode']); 
    google.maps.event.addListener(_autocomplete, 'place_changed', function() 
    { 
     //processing code 
    }); 
} 

function CreateElem() 
{ 
    var _id = "AutoCompl" + _autoComplCounter; 
    _autoComplCounter++; 

    var container = document.getElementById('AutoComplInputs'); 
    container.innerHTML += "<br>" + _id; 

    var _elem_for_upd = document.createElement("input"); 
    _elem_for_upd.type = "text"; 
    _elem_for_upd.id = _id; 
    container.appendChild(_elem_for_upd); 

    assignAutoCompl(_id); 
} 
</script> 
</head> 
<body> 
    <div id="AutoComplInputs"></div> 
    <input type='button' value='Add' onclick='CreateElem();'> 
</body> 
</html> 

但是,當我按下按鈕,自動完成只對最後的輸入,以及所有prevoius會斷裂。我認爲,它可以連接到動態創建的投入,如下面的代碼工作正常:

<html> 
<head> 
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script> 
<script type="text/javascript"> 
var _autoComplCounter = 0; 

function assignAutoCompl(_id) 
{ 
    document.getElementById(_id).hidden = false; 
    var _autocomplete = new google.maps.places.Autocomplete(document.getElementById(_id)); 
    _autocomplete.setTypes(['geocode']); 
    google.maps.event.addListener(_autocomplete, 'place_changed', function() 
    { 
     //processing code 
    }); 
} 

function CreateElem() 
{ 
    assignAutoCompl("AutoCompl0"); 
    assignAutoCompl("AutoCompl1"); 
} 
</script> 
</head> 
<body> 
    <div id="AutoComplInputs"> 
     <input id="AutoCompl0" type="text" hidden> 
     <input id="AutoCompl1" type="text" hidden> 
    </div> 
    <input type='button' value='Add' onclick='CreateElem();'> 
</body> 
</html> 

我不明白我在做什麼錯?

回答

0

不要使用innerHTML要將內容添加到container,您將失去綁定到現有元素的所有處理程序。

使用的appendChild代替:

container.appendChild(document.createElement('br')); 
container.appendChild(document.createTextNode(_id)); 
+0

謝謝你的幫助,它的作品! – user2289482