我有一个动态生成的元素:
// gathers the name of the file the user is uploading
let fileName = escape(e.target.files[0].name).slice(0,9);
let icon = $(` // this extra space is for readability on SO
<div class="fileImage" id="${fileName}">
<div class="glyph-stack">
<i class="glyphicon glyphicon-file file-icon"></i>
<i class="glyphicon glyphicon-file file-icon overlay"></i>
<i class="glyphicon glyphicon-remove file-icon" onclick="removeFile(${fileName})"></i>
</div>
<span class="file-title">${fileName}</span>
</div>`);
当我将元素附加到 DOM 并检查它时,${fileName} 的所有实例都正确显示。如果上传名为 freeicons.zip 的文件,则“freeicons”会出现在我放置 ${fileName} 的所有位置。但是,一旦在 onclick 处理程序中调用removeFile 函数:
function removeFile(fileName){
$('#'+fileName).remove();
}
函数内的变量 fileName 不再等于“freeicons”。当我检查它时,变量设置为 div#freeicons.fileImage,它是整个元素的选择器。
如果在 onclick 处理程序调用removeFile() 中,我将 ${fileName} 用单引号引起来:
`onclick="removeFile('${fileName}')"`
我在removeFile()中得到了字符串“freeicons”。
为什么在第一种情况下它用元素选择器替换字符串?这是 JQuery 在创建这个小元素树时正在做的事情吗?
最佳答案
fileName
是一个字符串,不带引号,在 onclick
处传递给函数的参数被解释为全局标识符
function removeFile(fn) {
console.log(fn)
}
let fileName = "abc";
let el = `<div onclick="removeFile('${fileName}')">click</div>`;
$("body").append(el);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
function removeFile(fn) {
console.log(fn)
}
let fileName = "abc";
// `abc` is not defined at `catch`, where `id` is not set to `fileName`
let el = `<div onclick="try {removeFile(${fileName})} catch(err) {console.error(err)}">click</div>`;
$("body").append(el);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
Why does this string get changed to full element selector?
document
中元素的 id
是全局的,属性事件处理程序是全局的。如果参数周围没有引号,则会引用全局 id
freeicons
,从而导致 DOM
元素 #freeicon
为在全局事件处理程序属性事件函数中记录
function removeFile(fn) {
console.log(fn)
}
let fileName = "abc";
// `abc` references the global `id` `"abc"`
let el = `<div id="${fileName}" onclick="try {removeFile(${fileName})} catch(err) {console.error(err)}">click</div>`;
$("body").append(el);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
关于javascript - 为什么这个字符串会变成完整的元素选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46832574/