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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4454593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 11:31:53  来源:igfitidea点击:

How to access id attribute of any element in Raphael

javascriptjqueryraphaelsetattribute

提问by sgbharadwaj

I'm using Raphael for drawing some elements on a website. The elements include rectangle, line (path). I have given an id to the path element and trying to access it in the onclick event of that line. but when I do an alert of the id, nothing is visible. Following is the code snippet

我正在使用 Raphael 在网站上绘制一些元素。元素包括矩形、线(路径)。我已经为 path 元素提供了一个 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"));
}

Can anyone please tell me what is the problem with the above code. Any pointer will be helpful.

谁能告诉我上面的代码有什么问题。任何指针都会有所帮助。

Thanks

谢谢

回答by Zecc

Are you sure you don't want to write $(t.node).attr('id','Hello');instead?

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

Update: someone just downvoted this answer. And I truly feel obligated to point out this way of setting the id isn't particularly good. You would be better off using:

更新:有人只是低估了这个答案。我真的觉得有义务指出这种设置 id 的方式并不是特别好。你最好使用:

t.node.id = 'Hello';

I wish there was a way to credit Juan Mendes, other than upvoting his comment to this answer.

我希望有一种方法可以归功于胡安门德斯,而不是支持他对这个答案的评论。

回答by Guillaume Gervais

Try this:

试试这个:

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...
}

Basically you are creating a new property called "id" on your Raphael line instance variable "t". It's kind of hacking, in my opinion, but it does the trick just fine.

基本上,您是在 Raphael 线实例变量“t”上创建一个名为“id”的新属性。在我看来,这有点像黑客攻击,但它的效果很好。

回答by Juan Mendes

Try setting the handler using jquery

尝试使用 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"));
}