[英]How to get value of dynamic input in vanilla JavaScript?
I'm loading a dynamic header with a dynamic hidden input from php by doing an ajax request.我正在通过执行 ajax 请求从 php 加载带有动态隐藏输入的动态标头。 The input gets created fine.
输入创建得很好。 The problem is not there.
问题不在这里。 Below the same page I'm using plain javascript to get the value of that dynamic input.
在同一页面下方,我使用普通的 javascript 来获取该动态输入的值。 The Ajax and the javascript are two different codes.
Ajax 和 javascript 是两种不同的代码。 If they were not, I would simply load from ajax success but I can't do this here.
如果不是,我会简单地从 ajax 成功加载,但我不能在这里这样做。
Problem is, in the console I get this error :问题是,在控制台中我收到此错误:
TypeError: document.getElementById(...) is null
类型错误:document.getElementById(...) 为空
How can I fix this?我怎样才能解决这个问题?
hidden input隐藏输入
<input id="appStatus" type="hidden" value="0">
javascript javascript
window.onload = function() {
var app_mode = document.getElementById('appStatus').value;
if (app_mode === 0) {//dev
var stripe = Stripe('pk_test_xxxx');
} else {//live prod
var stripe = Stripe('pk_live_xxxx');
}
};
You are calling document.getElementById('appStatus').value before your input field is generated by ajax request.在 ajax 请求生成输入字段之前,您正在调用 document.getElementById('appStatus').value。
Use Promise for this为此使用 Promise
function getInput() {
return new Promise((resolve, reject) => {
$.ajax({
...,
success: function(response) {
resolve(response);
},
error: function() {
reject();
}
});
});
}
window.onload = function() {
getInput().then(response => {
var app_mode = document.getElementById('appStatus').value;
if (app_mode === 0) {//dev
var stripe = Stripe('pk_test_xxxx');
} else {//live prod
var stripe = Stripe('pk_live_xxxx');
})
}
Consider setTimeout
function as success
function将
setTimeout
函数视为success
函数
Add event DOMNodeInserted
添加事件
DOMNodeInserted
When new element is inserted in document then function is automatically called在文档中插入新元素时,将自动调用函数
document.body.addEventListener("DOMNodeInserted",function() { var app_mode = document.getElementById('appStatus'); if(!app_mode) return; console.log(app_mode.value); }); setTimeout(()=>{ document.querySelector("div").innerHTML = '<input id="appStatus" type="text" value="0">'; },3000);
<div></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.