简体   繁体   中英

How to get html to print return value of javascript function?

What is the preferred syntax to get html to print return value of javascript function?

function produceMessage(){
    var msg= 'Hello<br />';
    return msg;
}

EDIT: Yikes, too many answers without me clarifying what I meant. I know how to do it via the script tag. However, let's say I wanted to make the message red. Would I just encase the script tag inside my css like so?

<div style="color:red><script>document.write(produceMessage())</script></div>

I guess my main question was, should you be using document.write to get the return values to print?

There are some options to do that.

One would be:

document.write(produceMessage())

Other would be appending some element in your document this way:

var span = document.createElement("span");
span.appendChild(document.createTextNode(produceMessage()));
document.body.appendChild(span);

Or just:

document.body.appendChild(document.createTextNode(produceMessage()));

If you're using jQuery, you can do this:

$(document.body).append(produceMessage());

It depends what you're going for. I believe the closest thing JS has to print is:

document.write( produceMessage() );

However, it may be more prudent to place the value inside a span or a div of your choosing like:

document.getElementById("mySpanId").innerHTML = produceMessage();

if you really wanted to do that you could then do

<script type="text/javascript">
    document.write(produceMessage())
</script>

Wherever in the document you want the message.

<script type="text/javascript">
    document.write("<p>" + Date() + "</p>");
</script>

Is a good example.

Or you can tell javascript where to write it.

<script type="text/javascript">
    var elem = document.getElementById('myDiv');
    var msg= 'Hello<br />';
    elem.innerHTML = msg;
</script>

You can combine this with other functions to have function write content after being evaluated.

you could change the innerHtml on an element

function produceMessage(){
    var msg= 'Hello<br />';
     document.getElementById('someElement').innerHTML = msg;
}

Most likely you're looking for something like

var targetElement = document.getElementById('idOfTargetElement');
targetElement.innerHTML = produceMessage();

provided that this is not something which happens on page load, in which case it should already be there from the start.

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