簡體   English   中英

將變量傳遞給document.getElementById()

[英]pass variable to document.getElementById()

您好,我有一個函數,我需要將一個變量傳遞給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>

你幾乎是正確的。 采用:

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

引號表示文字值 如果不使用引號,則使用變量。

在HTML中,您確實希望引號傳遞一個字符串值:

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

現在應該做的是選擇ID為#theDiv的元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM