2017-10-19 42 views
2

我有一个会动态生成的元素:为什么这个字符串被改为全元素选择器?

// 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在创建这个小元素树时做的事情吗?

+0

@bassxzero函数体被包括在事件功能问 – guest271314

+0

是什么'$ {文件名}'这是一个新的jQuery的事情? – Huangism

+2

您不应该内联绑定JS处理程序。相反,只需将click事件绑定到remove图标(您可能不得不依赖事件冒泡,因为点击图标在运行时不存在)。当点击事件的回调被触发,只需调用'$(event.target).closest( 'fileImage')。remove()方法'就足够了。 – Terry

回答

5

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>

为什么这个字符串变成完整的元素选择器?

id元素在document是全局的,属性事件处理程序是全局的。而不围绕所述参数引号,全球idfreeicons被引用,从而导致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>

+0

就像一个清晰的点,我没有downvote,并我同意这没有意义。你有没有参考这种行为的文档?我想它 – Cruiser

+2

@Cruiser读了[使用全局事件处理程序的HTML中的属性变成那样“被认为是不好的做法”?(https://开头计算器。com/questions/36388227/when-did-using-global-event-handler-attributes-within-html-become-considered-ba?),[id](https://developer.mozilla.org/en-US/文档/网页/ HTML/Global_attributes/ID)。尝试'console.log(freeicons)' – guest271314

相关问题