Javascript 为什么将此字符串更改为完整元素选择器?
我有一个动态生成的元素:Javascript 为什么将此字符串更改为完整元素选择器?,javascript,jquery,Javascript,Jquery,我有一个动态生成的元素: // 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}">
// 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>`);
函数中的变量文件名不再等于“freeicons”。当我检查它时,变量被设置为div#freeicons.fileImage,它是整个元素的选择器
如果在对removeFile()的onclick处理程序调用中,我将${fileName}用单引号括起来:
`onclick="removeFile('${fileName}')"`
我在removeFile()中得到字符串“freeicons”
为什么在第一种情况下,它会用元素选择器替换字符串?这是JQuery创建这个小元素树时正在做的事情吗?
文件名
是一个字符串,没有引号,传递给函数的参数在onclick
被解释为全局标识符
函数删除文件(fn){
console.log(fn)
}
让fileName=“abc”;
让el=`click`;
$(“正文”)。附加(el)代码>
@bassxzero函数体包含在问题中什么是${fileName}
这是一个新的jquery东西??不应该内联绑定JS处理程序。相反,只需将click事件绑定到remove图标即可(由于click图标在运行时不存在,您可能必须依赖事件冒泡)。当触发click事件回调时,只需调用$(event.target).closest('.fileImage').remove()
就足够了。@这是ES6中模板文本中的字符串插值:为了清楚起见,我没有投反对票,我同意这是没有意义的。您是否有此行为的文档参考?我想好好读一读it@Cruiser , . 尝试console.log(免费图标)
`onclick="removeFile('${fileName}')"`