尝试动态传递 ids 会破坏函数:
<p id="email1" onclick="mailTo(this.id,'com','abc','info','My Website','I have a question for you: ')">Send us an email</p>
<p id="email2" onclick="mailTo(this.id,'org','xyz','support','My Other Website','I want to report a problem with your website.')">Report Website Problems</p>
硬编码document.querySelector('#email')
成功,但需要id是动态的。
控制台正确打印 var。
错误:qS.addEventListener 不是一个函数。
function mailTo(idx, tld, domain, account, site, bodyText) {
let qS = `document.querySelector('#${idx}')`;
console.log(qS);
let arrEmail = [tld, domain, account, site, bodyText];
const buildEmail = arr => `${arr[2]}@${arr[1]}.${arr[0]}?subject=From%20the%20${arr[3]}%20website&body=${arr[4]}`;
qS.addEventListener("click", event => {
let str = `mailto:${buildEmail(arrEmail)}`;
location.href = str;
});
}
最佳答案
动态构建选择器参数...
let qS = document.querySelector(`#${idx}`);
关于javascript - 如何将动态变量传递给 JS 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54791493/