[英]Can I pass an object as the parameter for an onClick function
I am currently trying to create an onclick event for a button that calls a separate function and passes uses an object as the parameter for this function.
我的代码如下所示:
async function getJourneyAwait(){
const routes = await getJourney();
var innerHTML = " ";
if(!(routes === null)) {
for (var i = 0; i < routes.length; i++){
console.log(routes[i])
console.log(typeof(routes[i]))
var route = routes[i]
innerHTML += '<p> Route ' + i+1 + ': <button onClick=startJourney(' + route + ')>Start Trip</button></p>'
}
document.getElementById('tripmessage').innerHTML = innerHTML;
}
}
function startJourney(route){
console.log(route);
}
当我尝试单击 Start Trip 按钮时,我收到一条错误消息:Uncaught SyntaxError: Unexpected end of input at.(index):1
当我检查按钮元素时,参数似乎存在某种错误,因为元素如下:
<button onclick="startJourney([object" object])="">Start Trip</button>
我尝试了多种不同的方法,在某些情况下,我能够让 function 运行,但是当我执行所有记录到控制台的操作时,这些都是未定义的。 例如,如果我删除“路由”两侧的加号和引号,function 会运行,但 undefined 会记录到控制台。
您看到的[object object]
是将您的route
object 转换为字符串格式的结果。
我建议以下两种方法之一:
createElement
, assign the startJourney function to the onclick property using button.onclick = function() { createJourney(route) ]}
and append it to the parent element.addEventListener("click", createJourney(route))
添加点击事件监听器编辑:正如@Teemu 所指出的,如果您使用选项#1,则必须将var i = 0
替换为let i = 0
因为在具有基于 let 的索引的循环中,通过循环的每次迭代都将具有带有循环 scope 的新变量 i。
您应该建议您使用Data 属性并以这种方式绑定您的按钮:
function getJourneyAwait(){ const routes = getJourney(); var innerHTML = " "; if(routes) { for (var i = 0; i < routes.length; i++){ var route = routes[i] innerHTML += '<p> Route ' + route + ': <button onclick="startJourney(this)" data-route="' + route + '">Start Trip</button></p>' } document.getElementById('tripmessage').innerHTML = innerHTML; } } function getJourney(){ return [1, 2, 4, 6] } function startJourney(element){ console.log(element.dataset.route); }
<div id="tripmessage"></div> <button onclick="getJourneyAwait()">GetJourney</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.