Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
I';我试图在javascript生成的html中生成onclick方法,它';它给了我一些非常奇怪的结果_Javascript_Html - Fatal编程技术网

I';我试图在javascript生成的html中生成onclick方法,它';它给了我一些非常奇怪的结果

I';我试图在javascript生成的html中生成onclick方法,它';它给了我一些非常奇怪的结果,javascript,html,Javascript,Html,这是我的台词 '<button onclick="deleteElement("' + instrument.name + '")">Delete this instrument</button>' “删除此仪器” 我原以为这只是输出到html的以下内容,当给出乐器“干净的男高音人声”时 删除此仪器 然而,事情停止了,当我在inspector中检查它实际生成的html时,它决定生成以下内容 <button onclick="deleteElement(" cl

这是我的台词

'<button onclick="deleteElement("' + instrument.name + '")">Delete this instrument</button>'
“删除此仪器”
我原以为这只是输出到html的以下内容,当给出乐器“干净的男高音人声”时

删除此仪器
然而,事情停止了,当我在inspector中检查它实际生成的html时,它决定生成以下内容

<button onclick="deleteElement(" clean="" tenor="" male="" vocals")"="">Delete this instrument</button>  
删除此仪器
我很困惑,弄不清楚这里发生了什么


我假设我遗漏了一些小东西,或者不了解javascript或html,我对web开发还是相当陌生。

您过度使用了双引号,这会混淆html解析器

一个好的经验法则是:对HTML元素使用双引号,对JavaScript使用单引号。或者更好的方法是,使用背景标记来进行标记

使用反勾号的示例:

let instrument={name:'干净的男高音歌手'};
让我开始吧=
`删除该文书`
这将产生:

删除此仪器

您可以建议以下方法:

使用data-attribute存储唯一标识符,如下所示

`<button data-instrument="${instrument.name}" class="delete-instrument-btn">Delete this instrument</button>`

如果要创建元素,可以这样做

函数创建(){
让container=document.getElementById('container');
让内容='文本内容';
container.innerText=内容;
返回容器
}


创建
啊,我明白了,傻我。这是有道理的,我以后会更加注意这一点。非常感谢。还有,那些“let”关键字是用来做什么的?@RobHoover我刚刚把那个“let”放进去声明和设置instrument.name。应该是
let instrument={name:'Clean男高音歌手}
我明白了,谢谢!我以前从未见过使用过“${}”这个东西,你叫它什么,这样我就可以进一步研究它了?@RobHoover,它叫a。非常感谢!你能提供更多细节或告诉我们你想做什么吗?
`<button data-instrument="${instrument.name}" class="delete-instrument-btn">Delete this instrument</button>`
// run the following script once the HTML has been fully rendered
window.addEventListener('DOMContentLoaded', () => {
 function handleDeleteInstrument(ev) {
  const instrument = ev.target.dataset.instrument;
  if (
    instrument === undefined || 
    instrument === null      ||
    instrument.length === 0
  ) {
    console.log('Invalid instrument name provided')
    return;
  }
  deleteElement(instrument);
 }

 Array
  .from(document.querySelectorAll('.delete-instrument-btn'))
  .forEach((btn) => {
    btn.addEventListener('click', handleDeleteInstrument);
  })
})