开发者

use button to write text to the page

开发者 https://www.devze.com 2023-04-11 16:16 出处:网络
I can do this with a alert but I want to print the results of a function directly to the web page. When the user clicks the car button I want the results from the car() function to write into my id=

I can do this with a alert but I want to print the results of a function directly to the web page.

When the user clicks the car button I want the results from the car() function to write into my id="mainContent" div.

if the user clicks the Ice Cream button I want the results from the ice cream button to replace what ever is in the mainContent div with the results开发者_如何学Go from the iceCream() function


var mainContent = document.getElementById('mainContent');
carButton.onclick = function() {
    mainContent.appendChild(document.createTextNode(car()));
}


Assuming you have some code like this:

<form id="ice_cream_form" action="fake" method="post">
    <input type="submit" value="Ice Cream" />
</form>

You could use some JavaScript code like this:

var form=document.getElementById("ice_cream_form");
var mainContent=document.getElementById("mainContent");
if(form.addEventListener) {
    form.addEventListener("submit", submitted, false);
}else if(form.attachEvent) {
    form.attachEvent("onsubmit", function() {
        return submitted(window.event);
    });
}
function submitted(event) {
    if("textContent" in mainContent) {
        mainContent.textContent=iceCream();
    }else{
        mainContent.innerText=iceCream();
    }
    event.preventDefault();
    event.stopPropagation();
    return false;
}

If iceCream returns HTML you want to display rather than plain text you want to display, you'll probably want to replace the part that changes textContent to just set innerHTML.

Alternatively, you could use inline event handlers (although I don't really like this method because it mixes content and behavior):

<input type="button" value="Ice Cream" onclick="document.getElementById('mainContent').textContent=iceCream(); return false;" />


When, for example, the car button is clicked, this code should be run:

document.getElementById("mainContent").appendChild(
    document.createTextNode(car())); /* ← there is the magic */

If you don’t know how to register this function to be launched in case of clicking the button.
Then do it like this:

var button = document.getElementById("idOfTheButton");
button.addEventListener("click",
    function()
    {
        document.getElementById("mainContent").appendChild(
            document.createTextNode(car()));
    }, 1);

Adapt this code appropriately for the other button and it will work too.

0

精彩评论

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

关注公众号