即使我的CSS中存在ID,document.getElementById也无法正常工作

时间:2014-06-21 19:17:01

标签: javascript html css

我试过搜索,但没有得到我的问题的有效答案。 我总是得到" null"当我致电document.getElementById("#"+id)并提醒Document not loaded时。

我的Javascript代码

function changeDisplay(id) {
    alert("#"+id);

    if (!document.getElementById("#"+id)) {
        alert("Document Not loaded");
    } else {

        if (id == "property_photos") {
            alert(id);
            document.getElementById("#property_photos").style.display = "block";
            document.getElementById("#property_details").style.display = "none";
            document.getElementById("#property_reviews").style.display = "none";
            alert(document.getElementById(id).style.display);
        }
        if (id == "property_details") {
            alert(id);
            document.getElementById("#property_photos").style.display = "none";
            document.getElementById("#property_details").style.display = "block";
            document.getElementById("#property_reviews").style.display = "none";
            alert(document.getElementById(id).style.display);
        }
        if (id == "property_reviews") {
            alert(id);
            document.getElementById("#property_photos").style.display = "none";
            document.getElementById("#property_details").style.display = "none";
            document.getElementById("#property_reviews").style.display = "block";
            alert(document.getElementById(id).style.display);

        }
    }
}

HTML

<li>
    <a href="#property_photos" onclick="changeDisplay('property_photos')">Photos</a>
</li>
<li>
    <a href="#property_details" onclick="changeDisplay('property_details')">Details</a>
</li>
<li>
    <a href="#property_reviews" onclick="changeDisplay('property_reviews')">Reviews</a>
</li>

CSS

#property_photos {
    display:none;
}
#property_details {
    display:block;
}
#property_reviews {
    display:none;
}

任何帮助都会感激不尽。这是一个简单的问题。我有相同的代码在不同的页面上工作但不在页面m工作。我甚至在定义函数之前调用.css文件,但错误仍然存​​在。

2 个答案:

答案 0 :(得分:4)

document.getElementById() 需要井号(#)符号。

答案 1 :(得分:1)

在使用JavaScript时,不要使用#符号来引用元素的ID。

您的

代码
alert("#"+id);

将是

alert(id);

只有在使用CSS或jQuery时才需要#数字符号。