0

我有以下在 IE 中运行良好的方法,但出现以下错误:

TypeError: hdnButton .click is not a function

当我在 Firefox 中使用它时。

function PopupTest() {
    var hdnButton = document.getElementById('div_btn').firstChild;
    hdnButton.click();
}

谁能建议如何解决这个问题?我无法找到任何解决方案。

4

2 回答 2

1

My guess (since you've shown no html) is that you have some white space (perhaps a line break) which IE is ignoring, but which FF is returning as a text node. If so, you should be able to skip over it with something like:

function PopupTest() {
    var hdnButton = document.getElementById('div_btn').firstChild;
    while (hdnButton.nodeType === 3)
        hdnButton = hdnButton.nextSibling;
    hdnButton.click();
}

...which works by using the .nodeType property to test whether the .firstChild is a text node (3 means text node; for more information see MDN). If it is, it takes the next sibling and tests its .nodeType, and so on until it finds an element that isn't a text node. (Of course this assumes there will be one.)

Alternatively if you know what tag the (non text node) first child should be you could select it on that basis, e.g., if it's actually a <button> element:

hdnButton = document.getElementById('div_btn').getElementsByTagName("button")[0];
hdnButton.click();

Or if you don't need to support IE<=7:

document.querySelector("#div_btn > :first-child").click();
于 2013-11-04T09:57:57.207 回答
0

Check if document.getElementById('div_btn').firstChild;

if it exists, maybe there is another error such a whitespace, or you are calling PopupTest() before the DOM is loaded.

Try:

<body onload="PopupTest()">
于 2013-11-04T09:59:32.067 回答