2013-04-06 165 views
-2

这现在工作正常,如何在没有数组的情况下完成工作(仅限于侦听器),我需要将代码更改为没有数组但功能相同。错误if语句

这是Javascript代码。它是一个简单的绘图应用。

$(document).ready(function(){ 
var x; 
var y; 
var canv = $("#myCanvas")[0]; 
var ctx = canv.getContext("2d"); 

var lines = new Array(); 

$("#myCanvas").click(function(event) 
{ 
    x = event.pageX - $("#myCanvas").offset().left; 
    y = event.pageY - $("#myCanvas").offset().top; 

    ctx.fillStyle = "#" + $("#barvaPolnila").val(); 
    ctx.strokeStyle = "#" + $("#barvaCrte").val(); 
    ctx.lineWidth = $("#sirina").val(); 

    fill = $("input[name=polni]").is(":checked"); 
    width = $("#dolzina").val(); 

    shape = $("input[@name='lik']:checked").val(); 

    if (shape == 'krog') { 
     ctx.beginPath(); 
     ctx.arc(x, y, width, 0*Math.PI, 2*Math.PI); 
     if(fill) 
      ctx.fill(); 
     else 
      ctx.stroke(); 
    } else if(shape == "kvadrat") { 
     ctx.rect(x, y, width, width); 
     if(fill) 
      ctx.fill(); 
     else 
      ctx.stroke(); 
    } else { 
     if(lines[0] !== undefined) { 
      ctx.moveTo(lines[lines.length-1][0], lines[lines.length-1][1]); 
      ctx.lineTo(x, y); 
      ctx.stroke(); 
     } else 
      ctx.beginPath(); 

     lines.push([x, y]); 
    } 
}); 


$("#skrij").click(function() { 
    gumb = $(this); 
    nadzornaPlosca = $("#nadzornaPlosca"); 
    nadzornaPlosca.slideToggle(400, function() { 
     if($(this).is(":visible")) { 
      gumb.attr("value", "-"); 
     } else { 
      gumb.attr("value", "+"); 
     } 
    }); 
}); 

$("#zakljuci").click(function() { 
    if(lines[0] !== undefined) { 
     ctx.moveTo(lines[lines.length-1][0], lines[lines.length-1][1]); 
     ctx.lineTo(lines[0][0], lines[0][1]); 
     ctx.stroke(); 

     if($("input[name=polni]").is(":checked")) { 
      ctx.beginPath(); 
      for(i = 0; i < lines.length; i++) { 
       ctx.lineTo(lines[i][0], lines[i][1]); 
      } 
      ctx.closePath(); 
      ctx.fill(); 
     } 
    } 
    lines = new Array(); 
}); 

$("input[name=lik]").change(function() { 
    lines = new Array(); 
}); 

$("#brisi").click(function() { 
    ctx.clearRect(0, 0, canv.width, canv.height); 
}) 
}); 

回答

1

如果你想给函数绑定到click事件的,你不使用if()声明。更新代码以使用回调函数的click()功能的jQuery如下:

$("#pokazi").click(function(function() { 
    $("#nadzornaPlosca").slideToggle("slow"); 
}); 

$("#brisi").click(function() { 
    ctx.clearRect(0,0, 500, 500); 
}); 
1

最后两位都有点坏了,你要附加的事件处理程序,但包括if和关闭,关闭功能是前定义如下:

$("#pokazi").click(function() { 
    $("#nadzornaPlosca").slideToggle("slow"); 
}); 

$("#brisi").click(function() { 
    ctx.clearRect(0,0, 500, 500); 
});