You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中为产品详情表格使用mailto功能

在JavaScript中为产品详情表格实现mailto功能

先修正你原代码的基础问题

你的代码里有两处明显错误:

  1. DOM方法拼写错误:getElemenById → getElementById
  2. 字符串拼接错误:body=+ "email" 无法正确插入变量值,应该用变量而非字符串字面量

修正后的基础版本:

function SendEmail() {
  var email = document.getElementById("list").value;
  // 用模板字符串简化拼接,避免语法错误
  window.location.href = `mailto:example@gmail.com?subject=enquiry&body=${email}`;
}

针对产品详情表格的扩展实现

如果要把表格里的产品信息自动带入邮件内容,需要先定位到当前行的产品数据,再构造mailto链接。

示例表格结构

<table id="productTable">
  <tr>
    <th>产品名称</th>
    <th>规格</th>
    <th>价格</th>
    <th>操作</th>
  </tr>
  <tr>
    <td class="prod-name">智能手表</td>
    <td class="prod-spec">42mm 黑色</td>
    <td class="prod-price">1299元</td>
    <td><button onclick="sendProductEnquiry(this)">咨询该产品</button></td>
  </tr>
  <tr>
    <td class="prod-name">蓝牙音箱</td>
    <td class="prod-spec">便携款 续航8小时</td>
    <td class="prod-price">299元</td>
    <td><button onclick="sendProductEnquiry(this)">咨询该产品</button></td>
  </tr>
</table>

对应的JavaScript函数

function sendProductEnquiry(btn) {
  // 通过按钮定位到所在的表格行
  const currentRow = btn.closest('tr');
  
  // 提取当前行的产品详情
  const prodName = currentRow.querySelector('.prod-name').textContent.trim();
  const prodSpec = currentRow.querySelector('.prod-spec').textContent.trim();
  const prodPrice = currentRow.querySelector('.prod-price').textContent.trim();
  
  // 获取收件人邮箱(如果是用户选择/输入的)
  const recipient = document.getElementById("list").value;

  // 对邮件主题和内容进行URL编码,避免特殊字符解析失败
  const subject = encodeURIComponent(`产品咨询:${prodName}`);
  const body = encodeURIComponent(`您好,我想咨询以下产品:
产品名称:${prodName}
规格:${prodSpec}
价格:${prodPrice}

请尽快与我联系,谢谢!`);

  // 触发mailto链接
  window.location.href = `mailto:${recipient}?subject=${subject}&body=${body}`;
}

核心注意点

  • URL编码:必须用encodeURIComponent处理主题和内容里的中文、空格、换行等特殊字符,否则mailto链接会失效
  • DOM定位:确保表格元素的类名/ID与JS选择器完全匹配,避免找不到元素
  • 模板字符串:用ES6模板字符串(反引号包裹)让字符串拼接更清晰,减少语法错误

内容的提问来源于stack exchange,提问作者Çlöd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:45:30