简体   繁体   中英

Could someone explain why my javascript is not working?

Could someone please explain where i am going wrong on getting my hidden DIV to display using Javascript. I have looked at previous answers to this and they do not seem to be working.

        .newinner
    {
        display: none;
        padding-left: 10px;
        padding-top: 10px;
        background: white;
        width: 905px;
        margin: auto;
        height: 400px;
    }
    </style>
    <script>
    function ShowDiv(newinner)
    {
        document.getElementsByClassName("newinner").style.display="block";
    }
    </script>

Below is the DIV

    <button type="button" name="faddress" value="Show Div" onClick="showDiv('newinner')" />Find Address</button></div>
    <div class="newform">
    <div class="newinner">
    <form>
    <div class="formtitle"><b>To request this brochure please fill out the form below.</b></div>
    <div class="ntitle"><b>First Name*:</b><br><select>
      <option value="title">Title</option>
      <option value="mr">Mr</option>
      <option value="mrs">Mrs</option>
      <option value="miss">Miss</option>
      <option value="ms">Ms</option>
    </select>
    </div>
    <div class="fname">
    <input type="firstname" name="fname" /></div>
    <div class="lname"><b>Last Name:*</b><input type="lastname" name="lname" /></div>
    </form>
    </div>
    </div>

newinner is defined as a class, and you are searching for a node which has id equal to newinner... moreover you are not calling ShowDiv() anywhere in the code you posted

-- Updates --

I see you've updated the question since my initial answer, but there are still several problems in the code.

document.getElementsByClassName returns all the elements with the given class; it's an array-like structure. So normally you've to loop over each element; but in this case you could use an id instead, and then the document.getElementById method, that returns only the selected element when found, or null otherwise.

So you can rewrite showDiv as:

function ShowDiv (id) {
    document.getElementById(id).style.display = "block";
}

<button type="button" name="faddress" onClick="showDiv('newinner')">
    Find Address
</button>

<div id="newinner">
    ...
</div>

Also keep in mind that the use of onClick attribute is good for fast prototyping or demo purpose; if you're going to use this code in production, I recommend you to use document.addEventListener instead.

您没有在页面中的任何位置调用该功能

If you want to use document.getElementById() method, then give your DIV an ID.

Just change your line 2 from <div class="newinner"> to <div class="newinner" id="newinner">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM