如何在Raphael中访问任何元素的id属性

8

我正在使用Raphael绘制网站上的一些元素,包括矩形和线(路径)。我已经给路径元素分配了一个id,并尝试在该行的onclick事件中访问它。但是当我弹出id时,没有显示任何内容。以下是代码片段:

function createLine() 
{ 
  var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
  t.attr('stroke-width','3');
  t.attr('id','Hello');
  t.node.onclick = processPathOnClick; 
}

function processPathOnClick() 
{
    alert($(this).attr("id"));
}

请问上面的代码有什么问题?欢迎提供任何线索。

谢谢。

3个回答

14

你确定不想写成$(t.node).attr('id','Hello');吗?

更新:有人刚刚给这个答案点了个踩。我真的感到有责任指出,这种设置id的方式并不是特别好。你最好使用:

t.node.id = 'Hello';

我希望有一种方法可以给Juan Mendes贡献的信用,除了为他在这个答案的评论投票。


15
这应该可行,但我对人们为什么要使用 jQuery 来设置节点的 ID 感到困惑,很多冗余代码。将其与 t.node.id = 'Hello' 进行比较。 - Ruan Mendes
@sgbharadwaj 呃,我刚试了一下,对我来说可以用。然后你在处理程序中重写为 $(this.node).attr('id') 了吗?无论如何,就像已经说过的那样,你只需编写 t.node.it = "Hello"alert(this.id) 在处理程序中即可。 - Zecc
根据Dmitry Baranovskiy(Raphael的创建者)在此帖子https://dev59.com/SVDTa4cB1Zd3GeqPGyui中的评论,节点不应该被访问,但那么我们还能用什么呢?我正在尝试使用多个raphael形状并使用Jquery操纵它们时遇到问题。 - XaolingBao

3

试试这个:

function createLine()  { 
    var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
    t.attr('stroke-width','3');
    t.id = 'Hello';
    t.node.onclick = processPathOnClick;
}

function processPathOnClick() {
    alert($(this).id);
    alert(this.id); // This should work too...
}

基本上,您正在为Raphael线实例变量“t”创建一个名为“id”的新属性。在我看来,这有点像黑客,但它完全可以胜任。

2

尝试使用 jQuery 设置处理程序

function createLine() 
{ 
  var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
  t.attr('stroke-width','3');
  t.attr('id','Hello');
  $(t.node).click(processPathOnClick);
}

function processPathOnClick() 
{
    alert($(this).attr("id"));
}

1
嗨Juan, 设置处理程序没有起作用。我将设置属性更改为t.node.setAttribute('id',pathId); 并访问它以警报($(this).attr('id'));这个方法有效。 - sgbharadwaj
那么这告诉你,在 Raphael 对象上设置 id 并不会将其设置在节点上。没有必要使用 jQuery 来设置 id。通过执行 t.node.id='my-id',你的代码会更简单,而你的处理程序只需使用 alert(this.id) 即可。 - Ruan Mendes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接