我的项目有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”,第二个警报以“未定义”的形式出现。
在 x3dSphere.js对象文件中 http://i.stack.imgur.com/SLRmM.png
时,第一张图片是Firefox中监视表达式的快照。在 main.js文件 http://i.stack.imgur.com/lqKI0.png
中,第一张图片是Firefox中监视表达式的图片。(抱歉,我没有发布图片的声誉)
正如您所看到的那样,对象方法没有接收到<变换#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文件?
答案 0 :(得分:0)
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"
。