开发者

Javascript inline output

In javascript suppose you have this piece of code:

<div>
    <script type="text/javascript">var output = 'abcdefg';</script>
</div>

Is there any way to simply "echo" (using PHP terminology) the contents of output into #test? That is, to output a string inline, assuming you have no standard way of traversing or selecting from the DOM?

document.write("..."); does write the contents of output, but in doing so, it replaces the entire document with the output.

The solution I'm looking for should a开发者_如何学编程ct the same way a PHP echo would: write the output into the document inline.


You'd have to use document.write [docs]:

<div id="test">
    <script type="text/javascript">document.write('abcdefg');</script>
</div>  

DEMO

With the caveat that it does not work in XHTML documents. See the documentation for more details.


"Kosher" code aside, yes.

document.write()


In standards-based browsers:

document.getElementByID("test").textContent = output;

For broader support, you could use text in jQuery (or the equivalent method if your library of choice):

$('#test').text(output);


If your code is in the div, then document.write('abcdefg') is the proper choice for inserting something inline at the point of execution.

Or, if your code is not inside the div, you can do this:

<div id="test">
</div>

<script type="text/javascript">
var output = 'abcdefg';
document.getElementById("test").innerHTML = output;
</script>

You will have to make sure that your code runs AFTER the page is loaded and the div is present.


You could write something like:

<div id="test">
  <script>
    document.getElementById('test').innerHTML = "stuff";
    //this line only changes content in the div with id="test", not the whole dom
  </script>
</div>

But you should avoid putting a script inside a div because it may be overwritten.


I know this is an old question but if anybody is still looking then here is a handy function that does the job.

function echo(text)
{
    document.body.appendChild(document.createElement("div")).appendChild(document.createTextNode(text));
}


console.log()

http://getfirebug.com/logging

also supported in chrome and ie 9.. watch out for backwards compatibly it will get you ie8 and down i think...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜