gpt4 book ai didi

javascript - 如何将动态变量传递给 JS 中的函数?

转载 作者:行者123 更新时间:2023-11-28 14:22:22 25 4
gpt4 key购买 nike

尝试动态传递 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;
});
}

沙盒:https://codesandbox.io/s/p8k45v350

最佳答案

动态构建选择器参数...

let qS = document.querySelector(`#${idx}`);

关于javascript - 如何将动态变量传递给 JS 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54791493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com