【发布时间】:2016-09-18 02:10:15
【问题描述】:
好的,所以我有一些动态生成的文本框,当我调用 .val() 时找不到它们的值。在页面加载时呈现的文本输入将返回一个带有 .val() 的值,但其余的都不会。
如果此示例不足以得到答案,那么我将使用我的实际代码编辑问题,但我已尽力准确地简化它。
JQuery:
numBoxes = 0
function newText(){
numBoxes++
$('<div id="' + numBoxes + '"><input id="soft_text_' + numBoxes +
'" type="text"></div>').insertBefore($('button#new'))
}
function logHard(){
console.log($('input#hard_text').val())
}
function logSoft(){
$('div').each(function(){
console.log($('input#soft_text_' + this.id).val())
})
}
HTML:
<html><body>
<input id="hard_text" type="text" name="first_text">
<button id="new" onclick="newText()">Add new text box</button>
<button onclick="logHard()">Log first text box</button>
<button onclick="logSoft()">Log new text boxes</button>
</body></html>
【问题讨论】:
-
可能是因为里面没有文字?
-
“我已尽力准确地简化它。” 简化很好,但应该是minimal reproducible example。在这种情况下,由于它是基于浏览器的技术,因此请使用 Stack Snippets(
<>工具栏按钮)使其成为 可运行 MCVE。 -
可能这就是你需要的Please check this link
-
你真的尝试过你的代码吗?它工作正常:jsfiddle.net/kfssqg0c(如果您的实际代码不起作用,则不代表您的实际代码)
-
"..动态生成的文本框..." "..在加载时呈现的将返回..rest 不会.." 听起来像是将事件绑定到元素的常见问题还不存在:stackoverflow.com/questions/203198/…