如何传递动态变量以在JS中起作用? [英] How can I pass a dynamic variable to function in JS?
本文介绍了如何传递动态变量以在JS中起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试动态传递ID会破坏功能:
Attempting to pass ids dynamically breaks function:
<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 is not a function.
Hard coding document.querySelector('#email')
is successful, but need id to be dynamic.
Console prints var correctly.
Err: qS.addEventListener is not a function.
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
推荐答案
仅动态生成选择器参数...
Build just the selector param dynamically...
let qS = document.querySelector(`#${idx}`);
这篇关于如何传递动态变量以在JS中起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文