我有这个 html 模板,我使用 jQuery 和 AJAX 从我的服务器获取 html 表单。当用户选择特定表单时,将从放置在该 div 中的服务器获取该表单:
<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 个隐藏字段,id 为“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
后尝试立即通过 id 搜索元素,而您实际上应该等到加载完成
$("#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);
});
关于Javascript/jQuery 将表单添加到页面,但无法访问 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40900196/