2017-09-13 69 views
1

我正在使用jQuery-SlotMachine,特別是隨機函數發生器。這是我的HTML:在jQuery老虎機中顯示活動元素的文本內容

<div id="machine1"> 
    <span class="option"> 
     <span>Example A</span> 
     <span>Example B</span> 
    </span> 
</div> 
<div id="machine2"> 
    <span class="option"> 
     <span>Example C</span> 
     <span>Example D</span> 
    </span> 
</div> 
<div id="results"> 
    <span></span> 
</div> 

這裏是我的JS:

var machine1 = $("#machine1").slotMachine({ 
    active : 0, 
    delay : 500 
}); 

var machine2 = $("#machine2").slotMachine({ 
    active : 1, 
    delay : 500, 
    direction: 'down' 
}); 

function onComplete(active){ 
    switch(this.element[0].id){ 
     case 'machine1': 
      $("#machine1Result").text(this.active); 
      break; 
     case 'machine2': 
      $("#machine2Result").text(this.active); 
      break; 
    } 

} 

$("#randomizeButton").click(function(){ 

    machine1.shuffle(5, onComplete); 

    setTimeout(function(){ 
     machine2.shuffle(5, onComplete); 
    }, 500); 

}); 

所以我想要做的就是吐出名爲「結果」的容器的結果。我知道this.active給了我當前元素的索引號,但是我想要顯示的是文本值。所以我想表現出像「例子B例子C」。我試過使用像var $ results = $('。active')這樣的東西。與$('#results')。html($ results);但jQuery不是我的強項。

回答

1

嘗試以下操作:

$(document).ready(function() { 
    var machine1 = $("#machine1").slotMachine({ 
    active: 0, 
    delay: 500 
    }); 

    var machine2 = $("#machine2").slotMachine({ 
    active: 1, 
    delay: 500, 
    direction: "down" 
    }); 

    var results; 

    function onComplete(active) { 
    switch (this.element[0].id) { 
     case "machine1": 
     $("#machine1Result").text(this.active); 
     results[0] = getMachineResult($('#machine1'), this.active); 
     break; 
     case "machine2": 
     $("#machine2Result").text(this.active); 
     results[1] = getMachineResult($('#machine2'), this.active); 
     break; 
    } 
    $("#results").text(results.join(", ")); 
    } 

    function getMachineResult(i_jqMachine, i_iActive){ 
     return i_jqMachine.find('span.option > span').eq(i_iActive + 1).text(); 
    } 

    $("#randomizeButton").click(function() { 
    results = []; 
    $("#results").css('color', 'white').text(""); 
    machine1.shuffle(5, onComplete); 
    setTimeout(function() { 
     machine2.shuffle(5, onComplete); 
    }, 500); 
    }); 
}); 

我初始化的結果陣列從每臺機器保存結果,因爲它完成。我已經添加了一個getMachineResult例程,它將根據機器的「活動」值檢索結果。然後我使用這個例程將結果存儲在數組中。串聯的數組然後顯示在#results容器中。

最後,當您單擊按鈕時,我清除了結果數組和結果。 css('color', 'white')就是這樣,我可以看到結果。

我認爲應該這樣做。

+0

嗯,非常感謝你的建議。我一直在玩這個。似乎無法得到它的工作。我在這裏製作了一個[codepen](https://codepen.io/simonfoust/pen/LzVEEZ?editors=1010#0)。 – simonfoust

+0

請參閱我編輯的解決方案。棘手。 – PerpetualStudent

+0

我在你的債務。 :) – simonfoust