错误:当试图使用Raphael获取元素的位置时,this.attr不是函数
Error : this.attr is not a function when trying to get the position of an element using Raphael
我是Rapahel的新手,我正在尝试获取元素单击时的位置。请在下面找到代码片段。它给了我一个错误,说this.attr不是函数。我确信我做错了,请告知。
<html>
<head>
<title>Raphael Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="raphael.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function initPage() {
var paper = new Raphael(document.getElementById('holder'), 1200, 500);
var nodeHeader = paper.rect(100,100,150,50,10);
nodeHeader.attr({
gradient: '90-#6BAA3A-#409400',
stroke: '#6BAA3A',
'stroke-width': 1,
cursor: "move"
});
nodeHeader.node.id='nodeHeader';
nodeHeader.node.onclick = function(){
alert(this.attr('x'));
};
};
</script>
<div id="holder"></div>
</body>
</html>
事件上下文中的"this"对象为您提供DOM节点,而不是围绕它并包含Raphael功能的Element对象。您可以重用创建时声明的上一个Element变量,也可以通过ID:动态检索Element对象
nodeHeader.node.onclick = function(){
// Re-use previous variable
alert(nodeHeader.attr("x"));
// Retrieve dynamically via ID
alert(paper.getById("nodeHeader").attr("x"));
};
您的问题是将"onClick"处理程序直接放在DOM对象(节点)上,而不是Raphael对象本身。因此,正如Luke所解释的,您在事件处理程序中接收DOM对象作为this指针。如果你把点击处理程序放在拉斐尔对象上,你就会在点击处理程序中收到拉斐尔对象。
试试这个,你会收到你的Raphael对象作为这个指针,正如预期的那样:
nodeHeader.click(function(event) {
console.log("%o, %o", this, event);
alert(this.attr('x'));
});
相关文章:
- jquery试图按名称获取按钮位置
- 我可以获得相对于被点击元素的确切点击位置吗
- $(this).prop('property') vs. this.property
- 谷歌地图固定位置覆盖
- 在单击任何位置时隐藏元素,而不检查每次DOM单击
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 循环比赛位置算法
- es6 相当于下划线查找位置
- jQuery循环在特定位置暂停
- 引导程序:在导航栏中,显示悬停在单个位置的基于Li Link的不同内容
- 自定义函数中的光标位置
- 安卓平台上的QWebView HTML5地理位置
- 在另一个函数中使用变量this
- this.router在AngularJS 2中未定义
- DIV并排,位置不正确
- 使用jQuery更改元素的顶部位置
- 在谷歌地图上绘制位置数据库
- reactjs this.refs vs document.getElementById
- 错误:当试图使用Raphael获取元素的位置时,this.attr不是函数
- 我把$(this)放在函数中的什么位置