[英]Uncaught ReferenceError: 'a' is not defined at HTMLButtonElement.onclick (gallery.html:1)
When I create a new div element, I want the button to perform an onClick event that will capture the ${Title} variable.当我创建一个新的 div 元素时,我希望按钮执行一个 onClick 事件,该事件将捕获 ${Title} 变量。 Then the getTitle(Title) function will take ${Title} as a parameter and use module.exports so that I can use this variable in another javascript file.然后 getTitle(Title) function 将 ${Title} 作为参数并使用 module.exports 以便我可以在另一个 javascript 文件中使用此变量。 (the way I use module.exports is through browserify.) (我使用 module.exports 的方式是通过 browserify。)
function createDiv(Title){
var div = document.createElement('div');
div.setAttribute('class', `column-photo ${Type} show`);
var newDiv =
`
<div class="content">
<button class="content-text" id="Btn" onClick="getTitle(${Title})">
</button>
</div>
`;
div.innerHTML = newDiv;
document.getElementById('someID').prepend(div);
}
function getTitle(Title){
var imageTitle = Title.value;
module.exports = imageTitle;
console.log(imageTitle);
}
However, the problem here is that it throws an error when I click the button: (${Title} = 'a' and filename is gallery.html)但是,这里的问题是当我单击按钮时它会引发错误: (${Title} = 'a' and filename is gallery.html)
Uncaught ReferenceError: 'a' is not defined
at HTMLButtonElement.onclick (gallery.html:1)
The other javascript file will import this variable.另一个 javascript 文件将导入此变量。 However, console.log(imageTitle.imageTitle) is undefined.但是,console.log(imageTitle.imageTitle) 是未定义的。 How do I fix this?我该如何解决?
var imageTitle = require('./file.js');
console.log(imageTitle.imageTitle);
When constructing the HTML element, you need to properly inject the function parameter.在构造 HTML 元素时,需要正确注入 function 参数。 The error lays in this line:错误在于这一行:
onClick="getTitle(${Title})"
if the Title
is "a"
, then after building the string, it becomes:如果Title
是"a"
,那么在构建字符串之后,它变成:
onClick="getTitle(a)"
which produces this error because a
is not defined anywhere.这会产生此错误,因为a
未在任何地方定义。
To fix this, change the line to this one:要解决此问题,请将行更改为这一行:
onClick="getTitle('${Title}')"
which will be properly resolved to:这将被正确解决为:
onClick="getTitle('a')"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.