使用Javascript函数更改onclick操作 [英] Change onclick action with a Javascript function
问题描述
我有一个按钮:
<button id="a" onclick="Foo()">Button A</button>
当我第一次单击此按钮时,我希望它执行Foo(正确执行):
When I click this button the first time, I want it to execute Foo (which it does correctly):
function Foo() {
document.getElementById("a").onclick = Bar();
}
我第一次单击按钮时要发生的事情是将onclick函数从Foo()
更改为Bar()
.到目前为止,我只能实现无限循环或完全没有变化. 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:
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)";
}
推荐答案
您的代码正在调用该函数并将返回值分配给onClick,也应该是"onclick".这就是它的外观.
Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.
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); }
这篇关于使用Javascript函数更改onclick操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!