简体   繁体   中英

How do I refresh div contents on button click

I have a script inside a div which I want to refresh when someone clicks a button with a unique ID.

I have some data which will be displayed inside the div - which I need to refresh without refreshing the whole page.

I've found a solution which changes a border colour but I can't quite simplify it to what I need. Here's what I have so far

 var storeColor = 'red'; $('#container').on('click', 'button', function() { var $p = $('#content p'); var tmp = $p.css('border-color'); $p.css('border-color', storeColor); storeColor = tmp; });
 </div> <button type="button">Refresh DIV</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div id="container"> Contents of div </div>

I think there are a few problems with your code... The button is outside of the container and thats the reason the click listener doesn't work. Inside the click function you try to access a paragraph p inside some element with the id content which doesn't exist in your code

 var storeColor = 'red'; $('#btnRefresh').on('click', function() { var $p = $('#container'); $p.css('background-color', 'red'); $p.html('hello world'); });
 <button type="button" id="btnRefresh">Refresh DIV</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div id="container"> Contents of div </div>

Why not try changing the entire inner content of the div dynamically using document.querySelector('.div').innerHTML = html string

The above will not refresh the page if used upon a button click. You may want to use the preventDefault in the button's event listener too.

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