多次使用onclick功能

时间:2014-05-08 17:02:40

标签: javascript onclick

想象一下,您正在使用图像来调用这样的函数:

<img src="images/next.png" alt="" class="transition opacity" onclick="nextQ()" />

你有一个功能:

function nextQ(id) {
var prevQuestion = 0;
var currentQuestion = 1;

prevQuestion++;
currentQuestion++;
var elem = document.getElementById("q" + prevQuestion);
elem.parentNode.removeChild(elem);

document.getElementById("q" + currentQuestion).style.cssText = 'display:inline;';
next.style.cssText = 'display:none;';}

我怎么能这样做,所以每次你点击图像功能发生。目前只有在您第一次点击它时才会发生,当您第二次点击时没有任何反应。

2 个答案:

答案 0 :(得分:1)

您的prevQuestion&amp;&amp;每当你运行该函数时,你的currentQuestion都会重置,如果你希望它们每次都增加它们使它们成为全局变量(把它们放在你的函数之外),就像这样:

var prevQuestion = 0;
var currentQuestion = 1;

function nextQ(id) {

    prevQuestion++;
    currentQuestion++;    

}

这是一个工作示例http://jsfiddle.net/Tt8f6/

答案 1 :(得分:1)

onclick="nextQ()"

仅仅是一个FYI,在标记中使用事件处理程序是不好的做法。请参阅此SO topic

格式化和缩进除了问题之外,每次执行函数时,用于保存状态的变量都会丢失并重新创建。您需要将它们移动到更高的范围并在那里进行管理:

var nextQ = (function() {
  var prevQuestion    = 0;
  var currentQuestion = 1;

  function nextQ() { // You never referenced the id argument.
    prevQuestion++;
    currentQuestion++;

    var elem = document.getElementById("q" + prevQuestion);
    elem.parentNode.removeChild(elem);

    document.getElementById("q" + currentQuestion).style.cssText = 'display:inline;';
    next.style.cssText = 'display:none;'; // This is not defined!
  }

  return nextQ;
})();

最后,上述代码不提供操纵或检查的方式。虽然功能和正确(最简单)的答案我会更进一步,真正抽象的东西:

function QuestionStateMachine(id_prefix) {
  this.id_prefix       = id_prefix;
  this.currentQuestion = 1;
}
QuestionStateMachine.prototype.nextQ = function() {
  var current  = this.currentQuestion++;
  var previous = current - 1;
  var next     = current + 1;

  var prevEl    = document.getElementById('' + this.id_prefix + previous);
  var currentEl = document.getElementById('' + this.id_prefix + current)
  var nextEl    = document.getElementById('' + this.id_prefix + next)

  prevEl.parentNode.removeChild(prevEl);
  currentEl.style.cssText = 'display:inline;';
  nextEl.style.cssText = 'display:none;';
};

var quizSM = new QuestionStateMachine('q');
document.getElementsByClassName('quiz-button').forEach(function(button) {
  button.addEventListener('click', quizSM.nextQ.bind(quizSM));
});