用于click()的选择器中的变量不起作用

时间:2015-01-11 23:19:31

标签: javascript jquery

我有一些应该响应jQuery脚本的按钮。按钮用于在网页上缩放和平移svg图像。因为我想在页面上有超过1个svg文件,所以需要我的代码来知道我想要缩放哪个图像。我也可以使用我的鼠标进行缩放和平移(拖动),这很好。

简短的例子

var currentID;

//get the id of the container around the image. This is: 'SVGfile' followed by a number
jQuery( ".svgcontainer" ).mousemove(function( event ) {
    currentID = jQuery(this).attr('id');      
});

var target1='#zoomInButtonSVGfile1';
var target2='#panRightButton'+currentID;

jQuery(target1).click(function(){ zoomIn(); });                    //this works, but is hardcoded
jQuery("#zoomOutButtonSVGfile1").click(function(){ zoomOut(); });  //this works, but is hardcoded
jQuery(target2).click(function(){ panRight(); });                  //this doesn't work
jQuery('#panLeftButton'+currentID).click(function(){ panLeft(); });//this doesn't work

在前2个opties中,我不使用变量,但是对其进行硬编码,然后它才有效,但它并没有达到我的目的。 其他2个选项应该在我所知的情况下以及搜索选项后起作用。不知怎的,它什么也没做......任何人都可以发现我的错误吗?

1 个答案:

答案 0 :(得分:0)

如果您要设置变量然后使用它来绑定事件,则事件绑定必须也会在.mousemove内发生。

jQuery( ".svgcontainer" ).mousemove(function( event ) {
   if(!jQuery(this).data("bind")){
      jQuery(this).data("bind", true);
      var currentID = jQuery(this).attr('id');    

      var target1='#zoomInButtonSVGfile1';
      var target2='#panRightButton'+currentID;

      jQuery(target1).click(function(){ zoomIn(); });
      jQuery("#zoomOutButtonSVGfile1").click(function(){ zoomOut(); });  
      jQuery(target2).click(function(){ panRight(); });                  
      jQuery('#panLeftButton'+currentID).click(function(){ panLeft(); });
   }
});