2016-11-30 82 views
0

我有这个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之后

回答

1

我认为问题是,你正在试图寻找由IDS元素,而你实际上应该等到装载完成

$("#divform").load(formurl, function(resonse, status){ 
     // you may check status here to check for successfull load 
     $("#divform").find("#xpnt").attr('value', 1).end() 
        .find("#ypnt").attr('value', 2); 
}); 
+0

它的工作!事实上,这是有道理的,我正在寻找当时实际上不存在的元素。现在隐藏的字段被正确填充。非常感激。 –