我试图在两点之间画线。我设法做到了,但问题是它只能工作一次。第二次我单击一个圆圈时没有任何反应
仅在现代浏览器中有效
var click = false;
var x1;
var y1;
var x2;
var y2;
$('circle').click(function () {
if (click == false) {
x1 = $(this).attr('cx')
y1 = $(this).attr('cy')
click = true;
} else {
click = false;
x2 = $(this).attr('cx');
y2 = $(this).attr('cy')
var x=$('<line x1="' + x1 + '" y1="' + y1 + '" x2="' + x2 + '" y2="' + y2 + '" stroke-width="30" stroke="green" stroke-linecap="round"/>')
$('svg').append(x)
$("body").html($("body").html());
}
})
line{
transition:.5s all;
stroke-dasharray:2000;
stroke-dashoffset:2000;
-webkit-animation:move 1s forwards;
}
@-webkit-keyframes move{
100%{
stroke-dashoffset:0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<svg width="800" height="800">
<circle cx="30" cy="30" r="30" />
<circle cx="120" cy="30" r="30" />
<circle cx="210" cy="30" r="30" />
<circle cx="300" cy="30" r="30" />
<circle cx="30" cy="30" r="30" />
<circle cx="120" cy="120" r="30" />
<circle cx="210" cy="120" r="30" />
<circle cx="300" cy="120" r="30" />
<circle cx="30" cy="120" r="30" />
<circle cx="30" cy="210" r="30" />
<circle cx="120" cy="210" r="30" />
<circle cx="210" cy="210" r="30" />
<circle cx="300" cy="210" r="30" />
<circle cx="120" cy="300" r="30" />
<circle cx="210" cy="300" r="30" />
<circle cx="300" cy="300" r="30" />
<circle cx="30" cy="300" r="30" />
</svg>
编辑:这似乎在摘要中起作用,但在小提琴http://jsfiddle.net/akshay7/m2g6w80y/4/中不起作用
最佳答案
事件处理程序仅绑定到当前选定的元素;它们必须在您的代码进行事件绑定调用时在页面上存在。
由于您正在使用替换内容
$("body").html($("body").html());
您需要使用Event Delegation委托事件方法使用.on()。
即
$(document).on('event','selector',callback_function)
例
$(document).on('click', 'circle', function () {
//Your code
});
代替
document
,您应该使用最近的静态容器。委托事件的优点是,它们可以处理以后在后代添加到文档中的后代元素中的事件。通过选择保证在附加委托事件处理程序时会出现的元素,我们可以使用委托事件将click事件绑定到动态创建的元素,并且还避免了频繁附加和删除事件处理程序的需要。
DEMO
关于jquery - jQuery单击仅工作一次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29773629/