0

我从w3schools中获取了这个示例并将其修改为此。下面的代码不起作用。

我打算做的是隐藏 id 为“demo1”的 div。它不工作。问题是什么?

<!DOCTYPE html>
<html>

<head>
    <script>
        function myFunction(div_id)
        {
            //here the div_id variable seems to unparsable by the DOM event
            document.getElementById(div_id).innerHTML = hello;
        }
    </script>
</head>


<body>

    <p>Click the button to trigger a function.</p>

    <button onclick="myFunction('demo1')">Click me</button>

    <div id="demo1"></div>
    <div id="demo2"></div>

</body>
</html>
4

2 回答 2

3

变量hello未定义。您可能希望将其设置innerHTMLString

function myFunction(div_id) {
    document.getElementById(div_id).innerHTML = "hello";
    // -----------------------------------------^-----^
}

演示:http: //jsfiddle.net/uzuKp/1/

即使您从 W3Schools 中获取了一个示例并对其进行了修改,我还是建议将事件与 HTML 分开,并将关联的数据存储在data-*属性中。在您的示例中,它可以是这样的:

<p>Click the button to trigger a function.</p>

<button data-div-id="demo1">Click me</button>
<button data-div-id="demo2">Click me</button>
<button data-div-id="demo1">Click me</button>

<div id="demo1">demo1</div>
<div id="demo2">demo2</div>

和 JS:

function clickHandler() {
    var targetDivId, targetDiv;
    targetDivId = this.getAttribute("data-div-id");
    targetDiv = document.getElementById(targetDivId);
    targetDiv.innerHTML = "Hello" + new Date().getTime();
}

function loadHandler() {
    var buttons, i, j, cur;
    buttons = document.getElementsByTagName("button");
    for (i = 0, j = buttons.length; i < j; i++) {
        cur = buttons[i];
        cur.onclick = clickHandler;
    }
}

window.onload = loadHandler;

演示:http: //jsfiddle.net/3K4RD/

虽然我也建议查看以下文章以了解绑定事件的不同方法:addEventListener vs onclick

我的最后一个建议是不要设置该innerHTML属性。您可能在这里有一个简单的示例,但通常最好使用 DOM 方法,例如appendChild(添加节点)和document.createTextNode(创建可附加的文本)。当然,这需要先清除内容,例如:

while (targetDiv.firstChild) {
    targetDiv.removeChild(targetDiv.firstChild);
}
targetDiv.appendChild(document.createTextNode("Hello"));

演示:http: //jsfiddle.net/52Kwe/

您还可以将需要设置为属性的特定字符串存储innerHTMLdata-*尤其是在按钮之间不同时)。


更新:

根据您最近的编辑,该style属性是一个特殊属性,它实际上是一个具有您需要设置的样式属性的特殊对象。因此,对于您的示例,您必须设置.style.display值,例如:

document.getElementById(div_id).style.display = "none";
于 2013-07-16T16:34:38.160 回答
0
document.getElementById(div_id).style.display = 'none';
document.getElementById(div_id).style.visibility= 'hidden';
于 2013-07-16T16:57:38.857 回答