javascript - 为元素内的 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>';
}
解决方案
是的你可以。您需要在那里发送箭头功能。尝试单击文本“初始内容”。
我没有你的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>
推荐阅读
- axios - Axios、Shopify Storefront API、“参数丢失或无效”、“解析错误”
- spring-boot - Keycloack 显示“登录超时。请重新登录。” 使用 SAML 时
- django - 购物车中 OrderItems 的 Django 总价
- google-cloud-platform - 如何通过 GCP/BigQuery API 查找传输作业和计划查询的引用表和目标表?
- comparator - 初始化使用比较器类排序的 TreeSet 的最大大小
- html - 带有 Django 的纯 CSS 径向计时器
- asp.net-mvc - 在 asp.net 中绑定剑道网格的问题
- react-native - 如何在 react-native 中与图像和白色文本形成对比
- laravel - 如何将此查询转换为雄辩的结构化查询
- javascript - 关于通过 ajax 发送 post 请求的有线错误