How can I pass a dynamic variable to function in JS?

こ雲淡風輕ζ 提交于 2019-12-13 20:37:18

问题


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>

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;
  });
}

Sandbox: https://codesandbox.io/s/p8k45v350


回答1:


Build just the selector param dynamically...

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



回答2:


This will help you:

function mailTo(...items)
{
console.log(items[0].id);
}
<p id="email1" onclick="mailTo(this,'com','abc','info','My Website','I have a question for you: ')">Send us an email</p>
<p id="email2" onclick="mailTo(this,'org','xyz','support','My Other Website','I want to report a problem with your website.')">Report Website Problems</p>



回答3:


If you change

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

to

    let qS = this;

your code works. But you don't need to supply the id to query for the element since you can access it with this.



来源:https://stackoverflow.com/questions/54791493/how-can-i-pass-a-dynamic-variable-to-function-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!