[英]Can you pass Javascript Variable from one function to another using HTML
I am attempting to pass Javascript from one function to the next through my an onclick() function on my webpage: 我试图通过我网页上的onclick()函数将Javascript从一个函数传递给另一个函数:
Within the first funciton I am writing a table and one part of which creates this cell. 在第一个函数中,我正在编写一张表格,其中一部分创建了此单元格。
table += "<td><a onclick=assetDetails(assetId) href='#'>"+title+"</a></td>";
This is taking the variable title
and passing it to my HTML page as a hyperlink to execute the assetDetails funciton on click. 这将获取变量title
,并将其作为超链接传递到我的HTML页面,以在单击时执行assetDetails函数。
function assetDetails(assetId){ console.log(assetId); }
My assetDetails function is formatted like the above. 我的assetDetails函数的格式如上所述。
When I click the hyperlink it tells me that the assetId variable is unidentified. 当我单击超链接时,它告诉我assetId变量未识别。
I have tried this: 我已经试过了:
table += "<td><a onclick=assetDetails("+assetId+") href='#'>"+title+"</a></td>";
This passes the value of my variable and tells me that it is unidentified as well. 这传递了我的变量的值,并告诉我它也未被识别。
Is there any way to do this? 有什么办法吗?
您应该将assestId定义为标记的属性,并在JS中通过getAttribute DOM函数访问该值。
您可能应该用以下引号将assetId
变量包装起来:
table += "<td><a onclick=assetDetails('"+assetId+"') href='#'>"+title+"</a></td>";
table += "<td><a onclick=assetDetails(assetId) href='#'>"+title+"</a></td>";
When this is in html assestId will not exists in the scope unless its a global variable in which case why pass it. 如果使用html格式,则assestId将不在范围内,除非它是全局变量,在这种情况下为什么要传递它。 Perhaps you was trying to do this. 也许您正在尝试这样做。
table += "<td><a onclick=assetDetails('" + assetId + "') href='#'>"+title+"</a></td>";
I think you are also missing some quotes. 我认为您也缺少一些报价。
I would recommend creating your table td using document.createElement("td"). 我建议使用document.createElement(“ td”)创建表td。 This way you can then assign a onlick to it using addEventListener. 然后,您可以使用addEventListener为其分配onlick。
You missed quotes inside the onclick function, try: 您错过了onclick函数中的引号,请尝试:
table += "<td><a onclick=assetDetails('"+assetId+"') href='#'>"+title+"</a></td>";
This should work because when you create the table string, 'assesId' is known and inserted into the string like: 这应该起作用,因为在创建表字符串时,“ assesId”是已知的,并插入到字符串中,如下所示:
var assetId = 'test';
var title = 'title';
var tsTest = "<td><a onclick=\"assetDetails('"+assetId+"')\" href='#'>"+title+"</a></td>";
becomes: 变成:
<td><a onclick="assetDetails('test')" href='#'>title</a></td>
But : this is the old way of doing this. 但是 :这是执行此操作的旧方法。 You could better use the dom api (document.createElement, etc.) or use a library like jQuery: 您最好使用dom api(document.createElement等)或使用类似jQuery的库:
var link = jQuery("<a href='#'>title</a>");
link.click(function() {
// assetId is still known when clicked because of js closure
console.log(assetId);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.