你好,我正在尝试使用 jQuery 使用 Ajax 创建一个带有函数 onchange 的输入,这是输入:
<input type="file" class="hidden-print btn-sm" id="btn1"
onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">
编辑:
<img id="blah" alt="Image 1" class="img-responsive" />
在我的 js 中我有这个:
var blah = 'blah';
html += '<input type="file" class="hidden-print btn-sm" id="btn1" onchange="document.getElementById('+ blah +').src = window.URL.createObjectURL(this.files[0])">';
我也试试
getElementById(' + "blah" + ') rest of the code...
但是我得到这个控制台错误:
无法将属性“src”设置为 null。我知道这是因为('blah')问题,因为在 HTML 代码中工作正常。
最佳答案
当变量值附加到字符串时,您需要在变量值两边加上引号。为此,您需要对字符串中的引号进行转义,这样它们就不会被解释为分隔字符串,为此您可以使用 \'
。试试这个:
html += '<input type="file" class="hidden-print btn-sm" id="btn1" onchange="document.getElementById(\''+ blah + '\').src = window.URL.createObjectURL(this.files[0])">';
关于javascript - 如何在 jQuery 中将变量与 ' ' 连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37888371/