使用Javascript函数更改onclick动作

24 浏览
0 Comments

使用Javascript函数更改onclick动作

我有一个按钮:


当我第一次点击这个按钮时,我希望它执行Foo函数(它执行正确):

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

我希望的是,当我第一次点击按钮时,将onclick函数从Foo()更改为Bar()。到目前为止,我只能实现无限循环或根本没有变化。 Bar()函数可能如下所示:

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

因此,单击此按钮只是交替调用哪个函数。我该如何使其正常工作?或者,有什么更好的方法来显示/隐藏帖子的完整文本?它最初是缩短的,我提供了一个按钮来“查看完整文本”。但是当我点击该按钮时,我希望用户能够再次点击按钮以使文本的长版本消失。

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

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 = "隐藏完整错误";
    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 = "显示完整错误";
    document.getElementById(id+"Button").onclick = "ShowError(id)";
}

0