简体   繁体   中英

Activate HTML button (onClick function) from javascript

How do I activate existing HTML button, say running the onClick function in specific button?

When using document.getElementById("Button ID").onclick I get the function with the parameters, like the following example. but how do I run the function?

Example , the document.getElementById("Button ID") result is:

ƒ onclick(event) {calculate('ABC',1,8)}

In this example, how do I run calculate('ABC',1,8) function from javascript?

您可以在按钮元素上调用click方法。

document.getElementById("Button ID").click()

You simply call the click() function on the same element.

document.getElementById("Button ID").click()

This will trigger the onclick handler.

  • A function is called using parenthesis () , ie: fn() .
  • What you're getting is the declaration of that function.

You need to call it as follow:

document.getElementById("Button ID").click();

I recommend you to read about addEventListener and Event click .

const calculate = (p1, p2, p3) => {
    return p2 + p3
}

document.getElementById("Button ID").onclick = () => {
    const res = calculate('ABC',1,8)
    alert (res)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM