首页 > 解决方案 > 为元素内的 onclick 函数添加参数

问题描述

嘿伙计们,我在为我在 div 内的 onclick 事件上调用的函数提供参数的语法方面遇到问题。

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

下面是我的代码。如果你知道应该怎么写,请告诉我。除非我将参数(参数)保留为空白,否则我目前什么也没有发生。

为了澄清,我需要知道如何添加 emails[index].id 作为下面称为 open_email() 的函数的参数。什么是正确的语法?我试过: open_email(emails[index].id) 和 open_email("emails[index].id")

 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>';
      }

标签: javascriptparameters

解决方案


是的你可以。您需要在那里发送箭头功能。尝试单击文本“初始内容”。

我没有你的open_email功能,所以我做了一个作为例子。

基本上,onclick 将执行() => open_email(emailIndexId)

<div id="text">Initial Content</div>
<script>
  textDiv = document.getElementById('text');

  const open_email = id => {
    textDiv.innerText = "Sent email to " + id;
  }

  const emailIndexId = 33;

  textDiv.onclick = () => open_email(emailIndexId) // IMPORTANT
</script>


推荐阅读