总之,我想在一个jsp页面中用javascript创建一个html obejct,但是' alert (GameObject1.loginurl);‘会警告'undefined’。
我是否在下面的代码中得到了一些错误?看起来'obj.appendChild‘有failed.But为什么?
var obj;
try {
obj = document.createElement("object");
obj.id = "GameObject1";
obj.name = "JavaGameObject1";
obj.setAttribute("classid", "clsid:72E6F181-D1B0-4C22-B0D7-4A0740EEAEF5");
obj.width = 640;
obj.height = 526;
var loginurl = document.createElement("param");
loginurl.setAttribute("name", "loginurl");
loginurl.setAttribute("value", "xx.xx.xx.xx:8080");
obj.appendChild(loginurl);
document.body.appendChild(obj);
alert(GameObject1.loginurl);
} catch (e) {
alert("Exception:" + e.message);
}发布于 2013-04-28 14:50:28
根据您的代码,GameObject1从未定义过。我认为您希望使用obj,因为它是ID GameObject1的HTML对象。
但是,我要指出的是,即使是obj.loginurl也仍然是未定义的,因为您创建了名为loginurl的子HTMLobject param,而不是HTML object obj的属性。(即您可能需要执行obj.loginurl = "xx.xx.xx.xx:8080"才能以您想要的方式访问它)
要获取子元素param的值,您可能需要类似obj.children[0].value的代码,它将返回您在loginurl对象上设置的值。或者,在您当前的作用域中,您可以只调用loginurl.value。
当通过obj.children[#]访问子元素时,最好检查该位置的元素是否存在,这样就不会到处抛出异常。
发布于 2013-04-28 15:03:55
要访问loginurl,您可以使用
alert(obj.getElementsByTagName("param")[0]);
alert(obj.getElementsByTagName("param")[0].name);
alert(obj.getElementsByTagName("param")[0].value);像你提到的那样访问是获取属性而不是子元素的正确方式。
GameObject1 // Will look for Object variable not the object with id "GameObject1" - You should use document.getElementById("GameObject1")
GameObject1.loginurl // will look for attribute and not the child elementhttps://stackoverflow.com/questions/16260365
复制相似问题