改变每次点击后的点击按钮的方式

问题描述 投票:0回答:1

我有一个ractive按钮,需要在每次点击后改变功能。

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内部解决这个问题。

javascript ractivejs
1个回答
1
投票

你可以保留一个当前步骤的值,并根据该值调用所需函数。

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>

希望这对你有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.