简体   繁体   中英

How do I refresh the contents of a single div

I'm implementing a simple web-page, in that page, I have multiple div objects, what I'm trying to do is refresh the contents of a single div based on the user clicking a button or entering text in an input field.

So far I've found solutions online that apply to php which I know nothing about to be honest, can somebody provide me with a solution using javascript or jquery and simple html?

The simplest route if you're new to all of this is to change the html of the div. Given a div with id "ponies", you can change its contents via:

document.getElementById("ponies").innerHTML = '<p>new html block</p>'

If you want to swap out a div contents for another, you can opt instead to alter the DOM tree by a createChild after the div, and then removing the div. The innerHTML approach, while simple to understand, is a bit of a blunt (and slow) tool, compared to modifying the DOM itself. But if you're doing it rarely, and the html is simple, who cares?

If you have a form input for a forename then you can do:

function showForename(forenameDiv) {
    var text = "<p>Your forename is " + document.getElementById(forenameDiv).text + "</p>";
    document.getElementById("ponies").innerHTML = text; 
}

And put the call in the button's onClick event:

<input type="button" value="Who am I?" onclick="showForename('forenameinput')" />

Where forenameinput is the id of the forename form input. To learn more about all this stuff, look at the w3schools website .

an example with jquery:

$("input.button").click(function(){
   $('div#content').load('ajax/test.php', function() {
      console.log('loaded.');
   });
});

Based on @PhilH s answer here a cleaner jQuery solution:

jQuery( '#yourInput' ).click( function(){
    jQuery( '#ponies' ).text( 'You wrote: ' + this.value );
} );

Even in jQuery you can type in pure HTML if you want:

jQuery( '#yourInput' ).click( function(){
    jQuery( '#ponies' ).html( '<span>You wrote: <b>' + this.value + '</b></span>' );
} );

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