我有一个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')
将在每个事件上再次执行(顺便说一下,这可能会影响性能)。为什么你认为这是唯一的问题呢? - yankee$(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$('#templine')
在每次鼠标移动事件上都能执行,因为线条应该随着鼠标的移动而改变。所以我认为这是正确的。在你的建议之后,我会尝试缩短我的代码,谢谢。 - Jonas