Stack Overflow 上的一个旧帖子讨论了如何使用 JavaScript 填写 mailto 电子邮件:
我对应用该技术很感兴趣,但无法使其发挥作用。
在下面的代码中,当我在 makecontact() 方法的 return false 上设置断点并查看它记录的 URL 时,它看起来很好。
但是浏览器没有打开电子邮件客户端。
如果我在提交按钮的 href 中硬编码相同的 URL,它会启动电子邮件客户端。
为什么设置href不起作用?
答案:这是错误的href。
固定版本:
<!-- TODO: Validate name and text fields and don't allow submit until they are valid. Limit total mailto URL length to 2000. -->
<form name="contact">
<br/>Reason for contact:
<br/>
<input type="radio" name="reason" value="Product Inquiry/Presales Questions" checked="checked"/>Product Inquiry/Presales Question<br/>
<input type="radio" name="reason" value="Support/Warranty"/>Support/Warranty<br/>
<input type="radio" name="reason" value="Feedback"/>Feedback<br/>
<input type="radio" name="reason" value="Other"/>Other<br/>
<input type="text" name="name" id="name"/>Your name:</div>
<textarea name="contacttext" rows="20" cols="60" id="contacttext"></textarea>
<button id="submit">Submit</button>
</form>
<script type="text/javascript" id="contactjs">
<!--
var submit = document.getElementById("submit");
function getreason() {
var radios, i, radio;
radios = document.getElementsByName("reason");
for (i = 0; i < radios.length; i += 1) {
radio = radios[i];
if (radio.checked) {
break;
}
}
return encodeURIComponent(radio.value);
}
function makecontact(e) {
var subject, name, text;
subject = getreason();
name = document.getElementById("name").value;
text = document.getElementById("contacttext").value;
body = "From: '" + name + "', Content: '" + text + "'";
body = encodeURIComponent(body);
document.location.href = "mailto:contact@analogperfection.com?Subject=" + subject + "&Body=" + body;
console.log(document.location.href);
e.preventDefault();
return false;
}
if (submit.addEventListener) {
submit.addEventListener("click", makecontact, true);
} else if (form.attachEvent) {
submit.attachEvent("onclick", makecontact);
} else {
submit.click = makecontact;
}
//-->
</script>
</div>