如何在jsp页面中使用javascript创建html对象

How to create a html obejct with javascript in a jsp page

本文关键字:javascript 创建 html 对象 jsp      更新时间:2023-09-26

所有,我想用javascript在jsp中创建一个html对象但是'alert(GameObject1.loginurl);'会提示'undefined'.

我在下面的代码中得到一些错误吗?看起来,"obj"。appendChild'已失败。但是为什么呢?

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);
}

根据您的代码,GameObject1从未定义过。我认为你想使用obj代替,因为这是ID GameObject1的HTML对象。

然而,我要注意的是,即使obj.loginurl仍然是未定义的,因为您创建了称为loginurl的子HTML对象param,而不是HTML对象obj的属性。(即。您需要执行obj.loginurl = "xx.xx.xx.xx:8080"以您想要的方式访问它)

要获得子元素param的值,您将需要类似obj.children[0].value的东西,它将返回您在loginurl对象上设置的值。或者,在当前作用域中,您可以直接调用loginurl.value

当通过obj.children[#]访问子元素时,最好检查该位置的元素是否存在,这样就不会到处抛出异常。

要访问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 element