2014-01-18 53 views
-1

我试图通过jQuery函数访问SVG元素的属性。我可以通过ID访问每个元素,但我真正想要的是通过'this'访问元素。使用jquery的'this'访问SVG元素属性?

function drawPPF(){ 
    if (!$("#spreadFormPPF1").is(":visible")) { 
    $(this).attr('y', 5); 
    $("#spreadFormPPF1").fadeIn("slow"); 
    } else if ($("#spreadFormPPF1").is(":visible") && !$("#spreadFormPPF2").is(":visible")) { 
     $(this).attr('y', 5); 
     $("#spreadFormPPF2").fadeIn("slow"); 
    } else if ($("#spreadFormPPF2").is(":visible")) 
    { 
    $(this).attr('y', 5); 
    $("#spreadFormPPF3").fadeIn("slow"); 
    $("#spreadFormPPFInstruct").fadeIn("slow"); 
    } 
}; 

和HTML是

<svg id="spreadOutSVG1" width="600px" height="200px" xmlns="http://www.w3.org/2000/svg" 
xmlns:xlink="http://www.w3.org/1999/xlink"> 
<image x="50" y="10" width="300" height="200" xlink:href="images/flipcard.jpg" id="card1"onclick="drawPPF();" /> 
<image x="60" y="10" width="300" height="200" xlink:href="images/flipcard.jpg" id="card2" onclick="drawPPF();" /> 
... 
</svg> 

当我“本”替换#卡1或#卡2,它做什么,我希望它(即图像移动到与Y Y = 5 = 10)。但是我真正想要发生的是无论选择哪个SVG元素 - 你知道,这个 - 都要改变它的属性,而不是一个特定的ID。我究竟做错了什么?谢谢 - 我是超级新手,感谢您的帮助!

+1

尝试'的onclick =“drawPPF.call(本);”' –

回答

1

您可以使用Function.call()到自定义上下文传递给一个函数执行

<svg id="spreadOutSVG1" width="600px" height="200px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
    <image x="50" y="10" width="300" height="200" xlink:href="images/flipcard.jpg" id="card1" onclick="drawPPF.call(this);" /> 
    <image x="60" y="10" width="300" height="200" xlink:href="images/flipcard.jpg" id="card2" onclick="drawPPF.call(this);" /> 
</svg> 
+0

谢谢,没有工作,但不幸的是,如果图像紧密重叠,它只会影响“顶部”图像。 ??? – sachiko

0

的一个好办法,找出哪些$(this)实际上是被打印出来到控制台,只要你点击任何的卡。

function drawPPF(){ 
    $this = $(this); 
    console.log($this); 
    .... 
} 

然后,打开火狐在Chrome开发人员工具(命令+期权+ i)或萤火虫(命令+期权+ I),你可以看到什么$(这)是看在控制台。

在那里你会发现$(this)是未定义的,因为你是触发函数内联。这其中的一个解决方案是通过jQuery的

$('#card1').on('click', function(){ 
    $this = $(this); 
    console.log($this); 
    ... //Rest of function, which would be same as top 
}); 

在这里你会看到每一个你点击一个卡上时,它会显示哪一个在控制台中点击事件添加到卡。

即使你有上面的函数定义方式,所有你需要做的是

$('#card1, #card2').on('click', drawPPF); 
+0

对不起,我无法弄清楚你的代码行应该走哪儿了。我无法为我做这项工作。 – sachiko