使用 Javascript 函数更改 onclick 操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5303899/
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-23 16:34:02  来源:igfitidea点击:

Change onclick action with a Javascript function

javascript

提问by Tony Stark

I have a button:

我有一个按钮:

<button id="a" onclick="Foo()">Button A</button>

When I click this button the first time, I want it to execute Foo (which it does correctly):

当我第一次单击此按钮时,我希望它执行 Foo (它正确执行):

function Foo() {
  document.getElementById("a").onclick = Bar();
}

What I want to happen when I click the button the first time is to change the onclick function from Foo()to Bar(). Thus far, I've only been able to achieve an infinite loop or no change at all. Bar()would look something like this:

当我第一次单击按钮时,我想要发生的事情是将 onclick 函数从 更改Foo()Bar()。到目前为止,我只能实现无限循环或根本没有变化。Bar()看起来像这样:

function Bar() {
  document.getElementById("a").onclick = Foo();
}

Thus, clicking this button is just alternating which function gets called. How can I get this to work? Alternatively, what's a better way to show/hide the full text of a post? It originally starts shorted, and I provide a button to "see the full text." But when I click that button I want users to be able to click the button again to have the long version of the text go away.

因此,单击此按钮只是交替调用哪个函数。我怎样才能让它发挥作用?或者,显示/隐藏帖子全文的更好方法是什么?它最初开始短路,我提供了一个按钮来“查看全文”。但是当我单击该按钮时,我希望用户能够再次单击该按钮以使文本的长版本消失。

Here's the full code, if it helps:

这是完整的代码,如果有帮助的话:

function ShowError(id) {
    document.getElementById(id).className = document.getElementById(id).className.replace(/\bheight_limited\b/, '');
    document.getElementById(id+"Text").className = document.getElementById(id+"Text").className.replace(/\bheight_limited\b/, '');
    document.getElementById(id+"Button").innerHTML = "HIDE FULL ERROR";
    document.getElementById(id+"Button").onclick = HideError(id);
}

function HideError(id) {
    document.getElementById(id).className += " height_limited";
    document.getElementById(id+"Text").className += " height_limited";
    document.getElementById(id+"Button").innerHTML = "SHOW FULL ERROR";
    document.getElementById(id+"Button").onclick = "ShowError(id)";
}

回答by Ryan

Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.

您的代码正在调用该函数并将返回值分配给 onClick,它也应该是“onclick”。这是它应该看起来的样子。

document.getElementById("a").onclick = Bar;

Looking at your other code you probably want to do something like this:

查看您的其他代码,您可能想要执行以下操作:

document.getElementById(id+"Button").onclick = function() { HideError(id); }

回答by Otuyh

var Foo = function(){
    document.getElementById( "a" ).setAttribute( "onClick", "javascript: Boo();" );
}

var Boo = function(){
    alert("test");
}

回答by John Giotta

Do not invoke the method when assigning the new onclickhandler.

分配新onclick处理程序时不要调用该方法。

Simply remove the parenthesis:

只需删除括号:

document.getElementById("a").onclick = Foo;

UPDATE (due to new information):

更新(由于新信息):

document.getElementById("a").onclick = function () { Foo(param); };

回答by ?ime Vidas

I recommend this approach:

我推荐这种方法:

Instead of having two click handlers, have only one function with a if-else statement. Let the state of the BUTTON element determine which branch of the if-else statement gets executed:

不是有两个点击处理程序,而是只有一个带有 if-else 语句的函数。让 BUTTON 元素的状态决定 if-else 语句的哪个分支被执行:

HTML:

HTML:

<button id="a" onclick="toggleError(this)">Button A</button>

JavaScript:

JavaScript:

function toggleError(button) { 
    if ( button.className === 'visible' ) {
        // HIDE ERROR
        button.className = '';
    } else {
        // SHOW ERROR
        button.className = 'visible';
    }
}

Live demo:http://jsfiddle.net/simevidas/hPQP9/

现场演示:http : //jsfiddle.net/simevidas/hPQP9/

回答by TheSatinKnight

Thanks to Jo?o Paulo Oliveira, this was my solution which includes a variable (which was my goal).

感谢 Jo?o Paulo Oliveira,这是我的解决方案,其中包含一个变量(这是我的目标)。

document.getElementById( "myID" ).setAttribute( "onClick", "myFunction("+VALUE+");" );

回答by Jo?o Paulo Oliveira

You could try changing the button attribute like this:

您可以尝试像这样更改按钮属性:

element.setAttribute( "onClick", "javascript: Boo();" );

回答by Richard Marskell - Drackir

What might be easier, is to have two buttons and show/hide them in your functions. (ie. display:none|block;) Each button could then have it's own onclick with whatever code you need.

可能更简单的是有两个按钮并在您的功能中显示/隐藏它们。(即。display:none|block;)然后每个按钮都可以使用您需要的任何代码拥有自己的 onclick。

So, at first button1would be display:blockand button2would be display:none. Then when you click button1it would switch button2to be display:blockand button1to be display:none.

所以,起初button1将是display:block并且button2将会是display:none。然后,当你点击button1它会切换button2display:blockbutton1display:none

回答by anotheruser1488182

For anyone, like me, trying to set a query string on the action and wondering why it's not working-

对于像我这样的任何人,尝试在操作上设置查询字符串并想知道为什么它不起作用 -

You cannot set a query string for a GET form submission, but I have found you can for a POST.

您无法为 GET 表单提交设置查询字符串,但我发现您可以为 POST 设置查询字符串。

For a GET submission you must set the values in hidden inputs e.g.

对于 GET 提交,您必须在隐藏输入中设置值,例如

an action of: "/handleformsubmission?foo=bar"would have be added as the hidden field like: <input type="hidden" name="foo" value="bar" />

一个动作:"/handleformsubmission?foo=bar"将被添加为隐藏字段,如:<input type="hidden" name="foo" value="bar" />

This can be done add dynamically in JavaScript as (where clickedButton is the submitted button that was clicked:

这可以在 JavaScript 中动态添加为(其中 clickedButton 是被点击的提交按钮:

var form = clickedButton.form;
var hidden = document.createElement("input");
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "foo");
hidden.setAttribute("value", "bar");
form.appendChild(hidden);

See this question for more info submitting a GET form with query string params and hidden params disappear

请参阅此问题以获取更多信息, 提交带有查询字符串参数和隐藏参数消失的 GET 表单