为什么此字符串会更改为完整元素选择器?

Cru*_*ser 2 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}">
           <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>`);
Run Code Online (Sandbox Code Playgroud)

当我将元素附加到DOM并检查它时,$ {fileName}的所有实例都会正确显示.如果上传了一个名为freeicons.zip的文件,那么在放置$ {fileName}的任何地方都会出现"freeicons".但是,一旦在onclick处理程序中调用removeFile函数:

 function removeFile(fileName){ 
    $('#'+fileName).remove();
 }
Run Code Online (Sandbox Code Playgroud)

函数内的变量fileName不再等于"freeicons".当我检查它时,变量被设置为div#freeicons.fileImage,它是整个元素的选择器.

如果在onclick处理程序中调用removeFile(),我将$ {fileName}包装在单引号中:

`onclick="removeFile('${fileName}')"`
Run Code Online (Sandbox Code Playgroud)

我在removeFile()中得到了字符串"freeicons".

为什么在第一种情况下它会用元素选择器替换字符串?这是JQuery在创建这个小元素树时所做的事情吗?

gue*_*314 5

fileName是一个字符串,没有引号传递给函数at的参数onclick被解释为全局标识符

function removeFile(fn) {
  console.log(fn)
}

let fileName = "abc";

let el = `<div onclick="removeFile('${fileName}')">click</div>`;

$("body").append(el);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
Run Code Online (Sandbox Code Playgroud)

为什么此字符串会更改为完整元素选择器?

idelement in document是全局的,属性事件处理程序是全局的.如果参数周围没有引号,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);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
Run Code Online (Sandbox Code Playgroud)

  • @Cruiser [什么时候在html中使用全局事件处理程序属性变成"被认为是不好的做法"?](/sf/ask/2547175921/ -become-consideration-ba?),[id](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id).试试`console.log(freeicons)` (2认同)