【问题标题】:How to create a html obejct with javascript in a jsp page如何在jsp页面中使用javascript创建html对象
【发布时间】:2013-04-28 06:44:02
【问题描述】:

所有,我想在 jsp 中使用 javascript 创建一个 html 对象 页面,但 'alert(GameObject1.loginurl);'将提醒“未定义”。

我在下面的代码中是否有一些错误? '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.loginurl得到什么?

标签: javascript html object appendchild param


【解决方案1】:

根据您的代码,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[#] 访问子元素时,最好检查该位置的元素是否存在,以免到处抛出异常。

【讨论】:

  • 谢谢,我可以通过 GameObject1.children[#] 获取值。
【解决方案2】:

要访问登录网址,您可以使用

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 2013-01-10
    • 2014-01-29
    • 2011-04-13
    相关资源
    最近更新 更多