我试图将动态创建的 id 传递给 getElementById,但是当我尝试记录它时,它显示未定义。
"<input type='text' class='span2' name='price' pattern='[0-9.]*' id='p'"+ field.id + "placeholder='Price' value='0' />"
控制台:
console.log(document.getElementById("p"+field.id).value);
console.log($("#p"+field.id).val());
两者都表示未定义。我做错了什么?
最佳答案
您连接 html 字符串的方式不正确,
...id='p'"+ field.id..
因此上面的代码片段将被评估为 id='p'Something
并且在渲染来自 field.id
的 something
时将是被视为属性
。
所以尝试这样写:
"<input type='text' class='span2' name='price' pattern='[0-9.]*' id='p"+ field.id + "' placeholder='Price' value='0' />"
//------------------------------------------------------------------^----------------^
//changed the position of quotes.
关于javascript - 将动态创建的 id 传递给 getElementById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812053/