我有一个会动态生成的元素:为什么这个字符串被改为全元素选择器?
// 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和检查它的$ {文件名}所有实例正确显示。如果上传一个名为freeicons.zip的文件,则在我放置$ {fileName}的位置出现“freeicons”。然而,一旦removeFile函数被调用的onclick处理程序:
function removeFile(fileName){
$('#'+fileName).remove();
}
函数内部的变量文件名就不再等同于“freeicons”。当我检查它,该变量被设置为DIV#freeicons.fileImage,这是整个元件的选择器。
如果在onclick处理程序调用removeFile()我用单引号包$ {文件名}:
`onclick="removeFile('${fileName}')"`
我得到的字符串 “freeicons” 内removeFile()。
为什么在第一种情况下它替换的元素选择的字符串?这是JQuery在创建这个小元素树时做的事情吗?
@bassxzero函数体被包括在事件功能问 – guest271314
是什么'$ {文件名}'这是一个新的jQuery的事情? – Huangism
您不应该内联绑定JS处理程序。相反,只需将click事件绑定到remove图标(您可能不得不依赖事件冒泡,因为点击图标在运行时不存在)。当点击事件的回调被触发,只需调用'$(event.target).closest( 'fileImage')。remove()方法'就足够了。 – Terry