Javascript/jQuery 将表单添加到页面,但无法访问 DOM

标签 javascript jquery html ajax forms

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

相关文章:

javascript - 在 html 表格中突出显示鼠标悬停时选定的行和列

javascript - 使用 jQuery 或 JS 获取没有 http/https 的链接的基本 url

javascript - Gatsby 在开发期间工作正常,但在构建期间抛出错误

jquery - 进出动画有问题

jquery - jScrollPane 覆盖绝对定位,如何重新启用?

javascript - 单击链接时关闭模式

javascript - jQuery getJSON 不发送 cookie

javascript - 其他通过html与node.js连接并显示mysql的方式

javascript - 有没有办法使用 javascript 从图像 src url 获取数字?

html - MySQLdb._exceptions.OperationalError : (1136, "Column count doesn' t 行 1 处的匹配值计数")