[英]Creating Javascript Object by id using jQuery selector from an external file
我的项目有3个文件-onesphere.html文件, main.js文件和x3dSphere.js文件。
在main.js中,我试图通过id创建一个由x3dSphere.js文件定义的对象。 如此处所示:
x3dSphere.js
//x3dSphere "Class" Definition
function x3dSphere(id) {
this.id = "#"+id;
this.position = $(id).attr('translation');
this.diffuseColor = $(id).attr('diffuseColor');
}
main.js
//main.js
$(document).ready(function(){
$("#moveShapes").click(function() {
var string = $("#b1").attr('translation'); //works
alert(string);
var ball = new x3dSphere("b1"); //does not work
alert(ball.position);
});
});
当我从main.js使用jQuery id选择器读取转换值时,它可以工作并且字符串警报也可以工作,但是当我尝试创建对象时,它会失败。 由于某种原因,当我使用我的对象时,它没有选择特定的变换元素。第一个警报正确打印出“ 0 0 0”,第二个警报显示为“ undefined”。
第一张图片是x3dSphere.js目标文件 http://i.stack.imgur.com/SLRmM.png中Firefox中监视表达式的快照。
第一张图片是main.js文件 http://i.stack.imgur.com/lqKI0.png中Firefox中监视表达式的快照。
(对不起,我还没有发布图像的声誉)
如您所见,对象方法未使用<transform#b1>,我不确定为什么。 我认为这可能与该对象/“类”定义在单独的文件中有关。
附件是我的完整html文件,因此您可以看到我尝试选择的元素的格式以及如何包含多个脚本文件。
onesphere.html
<!DOCTYPE html>
<html>
<head>
<title>X3D</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/spheres.css"></link>
<script src="js/lib/x3dom.js"></script>
<script src="js/lib/jquery.js"></script>
<script src="js/x3dSphere.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<h1> Ball </h1>
<div id="x3dcontent">
<button id="moveShapes" >Move Shapes</button>
<x3d width="500px" height="400px">
<scene>
<transform id="b1" DEF="b1" translation='0 0 0'>
<shape>
<appearance>
<material diffuseColor='1 0 0'></material>
</appearance>
<sphere></sphere>
</shape>
</transform>
</scene>
</x3d>
</div>
</body>
</html>
我应该如何更改x3dSphere.js以获得打印“ 0 0 0”的警报? 是否可以将x3dSphere保留为单独的javascript文件?
x3dSphere.js中的行:
this.position = $(id).attr('translation');
this.diffuseColor = $(id).attr('diffuseColor');
应该:
this.position = $(this.id).attr('translation');
this.diffuseColor = $(this.id).attr('diffuseColor');
通过仅使用id
而不使用this.id
,您将"b1"
传递给jQuery而不是"#b1"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.