如何传递动态变量以在JS中起作用?

时间:2019-02-20 16:50:10

标签: javascript variables literals

尝试动态传递ID会破坏功能:

<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.

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

3 个答案:

答案 0 :(得分:2)

这将帮助您:

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>

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

如果您更改

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

    let qS = this;

您的代码有效。但是您无需提供ID即可查询元素,因为您可以使用this来访问它。