简体   繁体   English

首次单击后更改按钮onclick

[英]Change button onclick after first click

I'm having some struggles getting this to work. 我正在努力使它起作用。 I have a button, and I want it to execute Javascript function A, and in that function A, i want to change the Onclick to function B. Thus getting as result when the user taps the button a SECOND time, it's executing B. With the 我有一个按钮,我希望它执行Javascript函数A,在该函数A中,我想将Onclick更改为函数B。因此,当用户在第二次单击该按钮时,它就会执行B。该

<Button onclick="A();">Click me</button>
<script>
Function A() {
document.getElementById("button").onclick=B();
}
Function B() {
Alert("hello world");
}

In function A(), it doesn't execute FIRST A and after that B, it instantly executes B. Could anyone help me? 在函数A()中,它不执行FIRST A,然后执行B,它立即执行B。有人可以帮我吗? Thanks :) 谢谢 :)

You're calling B with B() . 您正在使用B()调用B。

Use document.getElementById("button").onclick=B; 使用document.getElementById("button").onclick=B; . Note that there's no parentheses after B . 请注意, B之后没有括号。

When you write a function name with the parenthesis, like B() , that invokes the function immediately. 当您使用括号写函数名称时,例如B() ,它将立即调用该函数。 Instead, you'll want to set onclick to be just the name of the function, A or B . 相反,您需要将onclick设置为函数名称AB

Your overall solution could look something like this: 您的整体解决方案可能如下所示:

function A(event) {
  // Function logic...
  event.target.onclick = B;
}

function B() {
  // Function logic...
}

document.getElementById("button").onclick = A;

You can use Jquery to change any attribute of a button onclick. 您可以使用Jquery更改按钮onclick的任何属性。 Below, I update the onclick attribute to instead execute function B() 在下面,我更新onclick属性以代替执行函数B()

 function A() { $('#toggler').attr('onclick', 'B()'); } function B() { console.log('Updated to B()!'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="toggler" onclick="A()">Click me!</button> 

Use an id instead of the onclick for the button then target it from javascript like this: 使用id代替buttononclick ,然后从javascript定位它,如下所示:

 function b() { console.log('I am in B.') } function a() { console.log('I am inside A.'); button1.removeEventListener('click', a); button1.addEventListener('click', b); } var button1 = document.getElementById('button1'); // get the button element button1.addEventListener('click',a); // assigns a click listener to a() at the beginning 
 <Button id="button1">Click me</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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