将变量传递给document.getElementById()

时间:2018-04-21 19:48:10

标签: javascript

您好我有一个函数,我需要将变量传递给document.getElementById();

我的功能就像这样

        function showComment(theField) {
            var x = document.getElementById("theField");
            if (x.style.display === "none") {
                x.setAttribute('style', 'display: block !important');
            } else {
                x.setAttribute('style', 'display: none !important');
            }
        }

和我这样的html按钮

<button type="button" class="btn-reset" onclick="showComment(theDiv)"> Show/hide </button>

1 个答案:

答案 0 :(得分:4)

你几乎是对的。使用:

var x = document.getElementById(theField); // (no quotes)

引号表示字面值。如果不使用引号,则使用变量。

在HTML中,你想要引号来传递一个字符串值:

... onclick="showComment('theDiv')" ...

现在应该做的是选择标识为#theDiv的元素。

相关问题