[英]Multiple click actions - Javascript
我有一個ID為'draw'的按鈕,並且想從中獲取,每次我單擊該繪制按鈕時,都要進行下一個要處理的操作(即我的形狀)。 我嘗試了style.visibility,但是沒有用。 也許我做錯了。 但是,這是代碼:
window.onload = function() {
var canvas = document.getElementById('myCanvas'),
draw = document.getElementById('draw'),
clr = document.getElementById('clear'),
context = canvas.getContext('2d');
var grad = context.createLinearGradient(100,0,200,0);
function shapeOne(){
context.beginPath(); // circle
context.fillStyle = 'blue';
context.arc(200, 100, 100, 50 , 2 * Math.PI, false);
context.fill();
context.lineWidth = '1';
context.stroke();
context.closePath();
}
function shapeTwo(){
context.beginPath(); // rectangle
grad.addColorStop(0,"#0033cc");
grad.addColorStop(1,"#0066ff");
context.fillStyle=grad;
context.fillRect(120,40,160,120);
context.strokeStyle="black";
context.strokeRect(120,40,160,120);
context.closePath();
}
function shapeThree(){
context.beginPath(); // line
context.moveTo(280, 40);
context.lineTo(120, 160);
context.stroke();
context.closePath();
}
draw.addEventListener('click', shapeOne, false);
draw.addEventListener('click', shapeTwo, false);
draw.addEventListener('click', shapeThree, false);
clr.addEventListener('click', function(){
canvas.width = canvas.width;
}, false);
};
正如其他人所說,當前綁定到“ draw”元素的所有事件偵聽器將同時觸發。 確實不需要多個事件偵聽器。 您只需要知道當前要繪制什么形狀的方法即可。
因此,我將聲明一個名為currentShape
類的變量並將其設置為零。
var canvas = document.getElementById('myCanvas'),
draw = document.getElementById('draw'),
clr = document.getElementById('clear'),
context = canvas.getContext('2d');
var grad = context.createLinearGradient(100,0,200,0);
// Start current shape at 0
var currentShape = 0;
// More code ...
然后,我將創建一個數組,該數組基本上是您擁有的形狀繪制函數的列表。
像這樣:
var shapes = [shapeOne, shapeTwo, shapeThree]
然后,不要使用三個事件偵聽器,而是使用一個看起來像這樣的事件偵聽器:
draw.addEventListener('click', function(){
// Check if there is a function available for the current shape.
if(shapes[currentShape]) {
// If so, call that function and add one to the current shape.
shapes[currentShape]();
currentShape += 1;
} else { // If the function isn't available, then lets assume we have already drawn all the shapes and need to start again.
currentShape = 0;
shapes[currentShape]();
}
}, false);
您還可以通過許多其他方式來執行此操作。 包括使用switch語句 ,這可能會刪除一些代碼重復。
不,這不是這樣做的方法 ,因為當您將多個偵聽器添加到html元素的同一事件中時,所有偵聽器將同時觸發。
因此,您需要創建一個poll(函數數組) ,然后在單擊元素時將一個新函數放入一個數組中執行,然后另一個函數控制這些函數的執行 。
您可以使用一個函數數組,您的click事件會將函數放在該數組中,然后您可以在另一時間調用(如在stackoverflow問題上所說明的)。
如果要控制功能列表的 動態執行,此示例是更好的解決方案 。
如何添加功能列表:
var listRuns = [],
ind = 0;
$('#btnRun').click(function(){
var message = document.getElementById("txtMsg").value;
listRuns.push(function(){
run(message);
});
});
如何執行它們:
var runAll = function(){
console.log('called');
if (listRuns.length>ind){
listRuns[ind]();
ind++;
}
};
var idInterval = setInterval(function(){
runAll();
},1000);
因此,與用戶單擊多少無關,您將執行所有這些操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.