【发布时间】:2011-07-15 04:45:05
【问题描述】:
我有一个要添加元素的 SVG。而在mousemove这个元素应该会移动,所以我想选择未来存在的元素:
// #svgcanvas exist always
// #templine will exist in the future
$('#svgcanvas').bind('mousemove', function(e) {
$('#templine').setAttributeNS(null, "x2", e.pageX);
$('#templine').setAttributeNS(null, "y2", e.pageY);
});
这是在 click 事件上创建的 #templine 元素:
$('#svgcanvas').bind('click', function(e) {
var line = document.createElementNS(xmlns, "line");
line.setAttributeNS(null, "id", "templine");
line.setAttributeNS(null, "x1", points[0].x);
line.setAttributeNS(null, "y1", points[0].y);
line.setAttributeNS(null, "x2", e.pageX);
line.setAttributeNS(null, "y2", e.pageY);
line.setAttributeNS(null, "style", "stroke:rgb(100,100,100)");
document.getElementById('canvas').appendChild(line);
});
此代码不起作用,因为#templine 在绑定时不存在。有没有其他方法可以用 jQuery 解决这个问题?我曾尝试使用.live() 而不是.bind(),但这在这种情况下没有帮助。
【问题讨论】:
-
不,如果这是您的问题,还有其他问题。
$('#templine')将在每个事件上一次又一次地执行(顺便说一下,这可能会对性能产生影响)。为什么您认为这是问题所在而不是其他问题? -
我从你的代码中猜测会有多个
templine元素,所以使用class属性而不是id属性。 -
顺便说一句:我相信您的 svgcanvas/click 函数的最后 7 行可以缩短为
$(line).attr('id', '#templine').attr('x1',points[0].x).attr('y1', points[0].y).attr('x2', e.pageX).attr('y2', e.pageY).attr('style', 'stroke:rgb(100,100,100)').appendTo('#canvase');。如果 jQuery 在 svg 上的行为不奇怪... -
@yankee:我希望在每个 mousemove 事件上执行
$('#templine'),因为当鼠标移动时该行应该改变。所以我觉得是对的。根据您的建议,我会尽量缩短我的代码,谢谢。 -
@waitinforantrain:这段代码很简单,我只会在第一次点击时创建一个id为“templine”的元素。
标签: javascript jquery jquery-selectors svg