Javascript 为元素内的onclick函数添加参数

Javascript 为元素内的onclick函数添加参数,javascript,parameters,Javascript,Parameters,嘿,伙计们,我在为一个函数提供一个参数方面遇到了一个问题,我在div中的onclick事件中调用了这个函数 我可以调用函数open_email(),但在添加参数时不能调用,因为我要添加的参数是从另一个表单元素获得的,我不确定如何正确键入它 下面是我的代码。如果你知道该怎么写,请告诉我。除非我将参数(参数)保持为空,否则我目前不会发生任何事情 为了澄清,我需要知道如何将emails[index].id添加为下面名为open_email()的函数的参数。正确的语法是什么?我试过:打开电子邮件(ema

嘿,伙计们,我在为一个函数提供一个参数方面遇到了一个问题,我在div中的onclick事件中调用了这个函数

我可以调用函数open_email(),但在添加参数时不能调用,因为我要添加的参数是从另一个表单元素获得的,我不确定如何正确键入它

下面是我的代码。如果你知道该怎么写,请告诉我。除非我将参数(参数)保持为空,否则我目前不会发生任何事情

为了澄清,我需要知道如何将emails[index].id添加为下面名为open_email()的函数的参数。正确的语法是什么?我试过:打开电子邮件(emails[index].id)和打开电子邮件(“emails[index].id”)

for(index=0;index”+“subject:”+JSON.stringify(电子邮件[index].subject)+“

”+JSON.stringify(电子邮件[index].timestamp)+”; }否则{ element.innerHTML+=''+''发件人:“+JSON.stringify(电子邮件[index].sender”)+ “”+”主题:“+JSON.stringify(电子邮件[index].Subject)+”

“+JSON.stringify(电子邮件[index].timestamp)+”; }
是的,您可以。您需要在那里发送一个箭头函数。尝试单击文本“初始内容”

我没有你的
open_email
功能,所以我编了一个例子

基本上,onclick将执行open\u email(emailIndexId):

初始内容
textDiv=document.getElementById('text');
const open_email=id=>{
textDiv.innerText=“发送电子邮件至”+id;
}
const emailIndexId=33;
textDiv.onclick=()=>打开电子邮件(emailIndexId)//重要

请创建一个可运行的示例有太多的部分使其无法运行。我需要知道的是如何使用电子邮件[索引]执行“onclick=open_email();”部分.id作为一个参数。当我添加一个参数时,我似乎无法让它工作。如果有太多的部分让你,谁写的,使它可以运行--这是否意味着我们,谁不知道它,让它可以运行的部分太多了?它不需要运行。我只需要知道如何将一个参数放入“onclick=open_email()”中部分。当我将电子邮件[index].id作为参数时,当我单击它时,它不会起任何作用。当没有参数时,它会起作用。但我需要传递一个参数。参数是电子邮件[index]。idsorry我不确定为什么它未格式化。很抱歉,我认为我的问题令人困惑。我如何放置电子邮件[index].id作为div onclick事件的参数?
myDiv.onclick=()=>open_email(emails[index].id)
the=>的作用是什么?有没有办法把它放在onclick属性中呢?我不太明白你的方法。如何放置参数(emails[index].id)在onclick属性中?它是一个arrow函数,基本上相当于
myDiv.onclick=function(){open_email(emails[index].id)}
,但具有不同的作用域规则。其思想是创建一个中间人函数,该函数将使用必要的参数运行open_email函数
 for (index = 0; index < emails.length; index++) {
      if (emails[index].read == false) {
        element.innerHTML += '<div class="emails unread" onclick="open_email();">' + "From:" + JSON.stringify(emails[index].sender) +
          "<p class='subject'>" + "Subject: " + JSON.stringify(emails[index].subject) + "</p>" + JSON.stringify(emails[index].timestamp) + '</div>';
      } else {
        element.innerHTML += '<div class="emails">' + "From:" + JSON.stringify(emails[index].sender) +
          "<p>" + "Subject: " + JSON.stringify(emails[index].subject) + "</p>" + JSON.stringify(emails[index].timestamp) + '</div>';
      }