每次点击后更改点击按钮

change the on-click of a ractive button after each click

我有一个需要在每次点击后更改功能的活动按钮。

const template1 = '<button type="button" id="advanceButton" on-click="@this.advance()">Step1</button>'

ractive = new Ractive({
  el: '#container',
  template: template1,
  advance: function() {
    $("#advanceButton").html("Step2");
    
    //this.on-click change to advance2() //that that would be the desired behaviour
  }
});
ractive.on({
  advance2: function() {
    $("#advanceButton").html("Step3");
    //this.on-click change to advance3() //and so on...
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ractive/1.3.12/ractive.js"></script>
<div id="container"></div>

我尝试在 ractive 之外使用 $("#advanceButton").attr('onclick', 'advance2()') 来解决这个问题,但尽管它也不起作用,但我更愿意在 ractive 内部解决这个问题。

您可以保留当前步骤的值并基于该调用所需的函数。

const template1 = '<button type="button" id="advanceButton" on-click="@this.advance()">Step1</button>'

ractive = new Ractive({
  el: '#container',
  data: { step: 1 },
  template: template1,
  advance: function() {
    var c_step = this.get("step") + 1;
    if( c_step === 4 )
        c_step = 1;
    this.set( "step", c_step );
    
    console.log( "Current step: " + c_step );
    
    if( c_step === 1 )
        this.step1();
    else if( c_step === 2 )
        this.step2();
    else if( c_step === 3 )
        this.step3();
  },
  
  step1: function() {
    $("#advanceButton").html("Step1");
  },
  
  step2: function() {
    $("#advanceButton").html("Step2");
  },
  
  step3: function() {
    $("#advanceButton").html("Step3");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ractive/1.3.12/ractive.js"></script>
<div id="container"></div>

希望对您有所帮助。