Javascript 一个按钮触发另一个按钮单击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7532320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:37:45  来源:igfitidea点击:

One button firing another buttons click event

javascripthtml

提问by Adam

I'd like two submit buttons on a form i have my team building, one above the fold, and one below. I'm getting complaints from my tech team about adding it because it requires some server side coding to make sure the user doesn't click it more than once. Apparently they have it one button, but to add that validation to two would be a problem.

我想在我的团队建设表单上有两个提交按钮,一个在折叠上方,一个在下方。我收到了我的技术团队关于添加它的抱怨,因为它需要一些服务器端编码以确保用户不会多次单击它。显然他们只有一个按钮,但是将验证添加到两个按钮将是一个问题。

Can you not just call the button the same thing, with the same ID and wouldn't the form treat it as one button?

你能不能不只是用相同的 ID 调用相同的按钮,表单不会把它当作一个按钮吗?

Another option I thought would be for new button to fire a click even on the other button. Then they still have one click even for the form, but I get my two buttons. How would I write that?

我认为另一个选择是让新按钮即使在另一个按钮上也能触发点击。然后他们仍然可以单击表单,但我得到了两个按钮。我该怎么写?

Thanks, Adma

谢谢,阿德玛

回答by James Hill

I'm only familiar with ASP.net and C# buttons, but using C# you could wire two different buttons to the same click event handler. You could also do it client side by triggering the primary buttons click event with your secondary button. Here's a VERY simple example:

我只熟悉 ASP.net 和 C# 按钮,但使用 C# 可以将两个不同的按钮连接到同一个单击事件处理程序。您也可以通过使用辅助按钮触发主按钮单击事件来在客户端执行此操作。这是一个非常简单的例子:

HTML

HTML

<input type="button" id="primaryButton" onclick="ExistingLogic()" />
<input type="button" 
       id="secondaryButton" 
       onclick="document.getElementById('primaryButton').click()" />

回答by Itisha-systematix

<input type="button" id="primaryButton" onclick="ExistingLogic()" />
<input type="button" id="secondaryButton"/>

$('#secondaryButton').click(function(){
    $("#primaryButton").click();
})

回答by jessi

If you want to use vanillaJS to do this... here is a generic very long way (with functions for both to be clear what is happening).

如果你想使用 vanillaJS 来做到这一点......这里是一个通用的很长的路(有两个功能可以清楚发生了什么)。

html

html

<input type="button" id="primaryButton" />
<input type="button" id="secondaryButton"/>

script

脚本

const primary = document.getElementById('primaryButton');
const secondary = document.getElementById('secondaryButton');

function somePrimaryAction(e){
  e.preventDefault();
  console.log('you clicked the primary button');
}

function clickPrimaryButton(e){
  e.preventDefault();
  console.log('you clicked the secondary button');
  primary.click();
}

primary.addEventListener("click", somePrimaryAction, false);
secondary.addEventListener("click", clickPrimaryButton, false);