javascript noob… document write

2019-02-27 10:41发布

问题:

I'm trying to use Javascript to load more links in my nav bar.

This is what I tried; I just wanted one link in my nav to load more beneath it.

<a href="" onclick="show()"/>collections</a>
<script type="text/javascript">
function show() {
   document.write("collection 1 <br /> collection 2 <br /> etc... <br />");
}
</script>

Can anybody suggest a relevant tutorial or give me a hint?

回答1:

document.write should really only be used while the document is loading. Calling it after the document is loaded will clear the current document and write some new content. To add new content to the page, you would need to create new DOM objects and add them to the page or modify existing DOM objects.

Here's a small example of modifying the page you can see in action here: http://jsfiddle.net/jfriend00/zVS39/

HTML:

<a href="#" onclick="show()">collections</a>
<span id="moreText"></span>

Javascript:

function show() {
    var o = document.getElementById("moreText");
    o.innerHTML = "<br>collection 1 <br /> collection 2 <br /> etc... <br />";
}


回答2:

You can use innerHTML, or if you want to something more complex you could append a new element, for example:

HTML

<a href="" onclick="show()">collections</a>
<div id="hidden"></div>

Javascript

function show() {
var hidden= document.getElementById("hidden"),
    newElem = document.createElement("div");

newElem.innerHTML = "<br>collection 1 <br /> collection 2 <br /> etc... <br />";
newElem.style.color = "red";
hidden.appendChild(newElem);
}


回答3:

See Creating and modifying HTML from the WSC



回答4:

You didn't tell us what your problem is.

But this is wrong:

<a href="" onclick="show()"/>collections</a>

You have made your a self-closing, so "collections" isn't part of the link and </a> is orphaned/invalid. Thus your function isn't going to fire when you click on "collections".

Write:

<a href="" onclick="show()">collections</a>


回答5:

you can always use the innerHTML feature.

document.getElementById('someelement').innerHTML = "collection 1</br>collection2 ...";

So your HTML would look like:

<div id = "nav"></div>
<div id = "someelement></div>

So that text you wanna insert underneath your navigation will pop up in "somelement". You can also modify the css to do a show/hide type technique.