我有這個html模板,我使用jQuery和AJAX從我的服務器獲取html表單。當用戶的動產的具體形式,它是由放置在這個服務器獲取的div:Javascript/jQuery向頁面添加表單,但不能訪問DOM
<div id="divform" style="border:1px solid #3e8e41"></div>
用我的功能:
<script type="text/javascript">
//... setting the correct URL for GETing a specific form ...
//... the function:
$(document).ready(function(){
$("input[name=formfetch]").click(function(){ //The click event that triggers the asynchronous GET
$("#divform").html("...");
var formurl = detailurl.replace("rootslug", $(this).attr('slug')); //The URL for the GET
$("#divform").load(formurl); //GET + load at divform
var frm = $('#theform');
document.getElementById('xpnt').value = 1; //Trying to fill the hidden fields, this fails!
document.getElementById('ypnt').value = 2;
});
});
每個表單我取出並放入「divform」將有2隱藏字段,帶有'xpnt'和'ypnt'。我會在任何情況下使用我的函數來填充它們(在這種情況下,我只是將值1和2作爲測試值)。我可以獲取的形式,但問題是,當我嘗試訪問與document.getElementById
這些隱藏字段,然後修改它們的值,在瀏覽器(Chrome在這種情況下)控制檯顯示:
(index):113 Uncaught TypeError: Cannot set property 'value' of null at HTMLInputElement.
從我搜索和測試,我知道該網頁的來源不會改變,表格實際上不會出現在網頁源代碼中。這裏的問題是我放置在'divform'中的表單沒有被添加到頁面的HTML DOM中,因此通過這些方法變得「無法訪問」,如document.getElementById
?我該如何解決這個問題?
PS:(我有在獲取來自服務器的形式沒有問題)執行.load
之後
它的工作!事實上,這是有道理的,我正在尋找當時實際上不存在的元素。現在隱藏的字段被正確填充。非常感激。 –