我正在尝试创建一个基于用户输入绘制图形的简单应用程序。我正在使用Raphaël和jQuery。我想让用户在表单上输入他们的输入,然后绘制SVG图形。我遇到的问题是,当我在jQuery click事件中调用draw函数时,SVG对象会闪烁然后消失。下面有一个MWE。 (也许它可能更小。)如何在点击按钮后确保图形停留在那里?
<!doctype html>
<html>
<head>
<title>Example</title>
<meta charset="utf-8"/>
<script type="text/javascript" src="jquery-ui-1.10.4/jquery-1.10.2.js"></script>
<script type="text/javascript" src="jquery-ui-1.10.4/ui/jquery-ui.js"></script>
<link rel="stylesheet" href="jquery-ui-1.10.4/themes/base/jquery-ui.css" />
<script type="text/javascript" src="raphael-min.js"></script>
</head>
<body>
<form>
<button id="generate-button">Generate</button>
</form>
<div id="canvas"/>
<script>
function CustomObject() {
this.draw = function() {
// Creates canvas 320 × 200 at 10, 50
paper = Raphael("canvas", 100, 100 );
boundary = window.paper.rect( 5, 5, 25, 25 );
boundary.attr("stroke-dasharray" , "--" );
// Creates circle at x = 50, y = 40, with radius 10
circle = paper.circle(50, 40, 10);
// Sets the fill attribute of the circle to red (#f00)
circle.attr("fill", "#f00");
// Sets the stroke attribute of the circle to white
circle.attr("stroke", "#fff");
}
}
var plot = new CustomObject();
// plot.draw(); // if I call it here, the scene is drawn "normally"
$( "#generate-button" )
.button()
.click(function() {
plot.draw(); // when I call it here, the SVG flickers and disappears
});
</script>
</body>
</html>
答案 0 :(得分:1)
按钮的默认类型是提交,当在表单内部时,将尝试提交表单。
您的点击处理程序正在执行,然后提交导致闪烁的表单。
从表单中取出按钮或从click事件处理程序返回false,因为这将禁用浏览器默认操作。