[英]index.html:1 Uncaught ReferenceError: VARIABLE is not defined at HTMLDivElement.onclick
I am trying to pass a variable from an HTML file in a jquery selector that contains HTML tags to a JavaScript function. 我试图将包含HTML标记的jquery选择器中的HTML文件中的HTML变量传递给JavaScript函数。
var $tweeter = $('<div class="tweeter" onClick="userTweet(' + streams.home[index].user + ')"></div>');
Where userTweet()
is a function in my linked JavaScript file and streams.home[index].user
is an array of user objects with user
, message
, and created_at
keys. 其中
userTweet()
是链接的JavaScript文件中的函数,并且streams.home[index].user
是具有user
, message
和created_at
键的用户对象的数组。 When I click on the div, I get the error 当我单击div时,出现错误
index.html:1 Uncaught ReferenceError: VARIABLE is not defined at HTMLDivElement.onclick
With VARIABLE
being the user name in the user
property of streams.home[index]
VARIABLE
是streams.home[index]
的user
属性中的用户名
How can I pass this variable to run the function in my JavaScript file? 如何传递此变量以在JavaScript文件中运行该函数? Please let me know if you require any further information.
如果您需要任何进一步的信息,请告诉我。
Thanks! 谢谢!
Is your userTweet
available on window? 您的
userTweet
在窗口上可用吗? if so then 如果是的话
$('<div class="tweeter"/>').on('click', function() {
window.userTweet(streams.home[index].user)
})
You are victim of single quotes(') and double quotes(") here. 您是单引号(')和双引号(“)的受害者。
When you tried to do 当你尝试去做
var $tweeter = $('<div class="tweeter" onClick="userTweet(' + streams.home[index].user + ')"></div>');
// For Simplicity assuming streams.home[index].user value is 'mike'
Your string is not what you expected. 您的字符串不是您期望的。
This is string that formed: 这是形成的字符串:
<div class="tweeter" onClick="userTweet(mike)"></div>
// Note mike is not a value but as a variable here
This is what you expected it to be: 这是您期望的:
<div class="tweeter" onClick="userTweet('mike')"></div>
// Note 'mike' is value here
So when you called userTweet
you passed a variable mike
which doesn't exist and this error. 因此,当您调用
userTweet
您传递了一个不存在的变量mike
和此错误。
The difference in both the calls is userTweet(mike)
and userTweet('mike')
. 这两个调用的区别是
userTweet(mike)
和userTweet('mike')
。 On first call mike
is variable(your case) and on second one it's a value. 第一次调用
mike
是可变的(根据您的情况),而第二个mike
是一个值。
Would recommend you to follow this link over string and backticks in javascript as this provides solution to your problem. 建议您在javascript中的字符串和反引号上关注此链接,因为这可以解决您的问题。
Also just do this 也只是这样做
var $tweeter = $(`<div class="tweeter" onClick="userTweet(' ${streams.home[index].user} ')"></div>`);
// If on older version and new JavaScript is not supported then
var $tweeter = $('<div class="tweeter" onClick="userTweet(' + "'" + streams.home[index].user + "'" + ')"></div>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.