reload contents of div using javascript

狂风中的少年 提交于 2019-12-11 05:21:47

问题


I'm trying to reload the contents of div tag on button-click. I can do it with using:

function reload_div()
{   
    document.getElementById('div_id').innerHTML = 'blah blah blah';
}

but the problem is, that div tag contains thousands of lines and when I try to acomplish the div-reloading with previous function, the browser will be freezed. I was searching for a solution on stackoverflow but all what I found is with using ajax or jquery and I haven't used those library before. So, can I reload the div contents using javascript and html only? Thanks.


回答1:


I'm not sure why you would want to load so much content with javascript in the first place, but you could always put the javascript in an external file so the browser could cache it. That should help if it's the browser loading the script that is causing the page to freeze up.

Feel free to post more code and I'll take a look if that doesn't do it for you.




回答2:


You can't exactly "refresh" the content I don't think, I've never heard of that. (however, I'm not an expert) However, I have heard of switching out the content with javascript, try something link this:

here's your button & div with content:

<a href="divrefresh()">Refresh it!</a>
<div id="content"><p>Some Stuff!</p></div>

Here's the js underlying, you've got a function which is used above in the link.

function divrefresh() {
     document.getElementById('content').innerHTML = "Some new stuff!"
}

ETA: Oops, I see the rest of your post now. I'm not sure why that would freeze the browser. Try jQuery, it's really easy to use, that's why everyone loves it. If you've found a jQuery solution, I wouldn't hesitate to try it out! Post it and I can help you.

If you REALLY don't want to use jQuery or Ajax, then I think the only other solution is to put the lines in their own HTML document, have an iframe, and refresh the iframe.




回答3:


You could try using removeChild, in a variety of ways (I'm not sure whether the following code would freeze the browser or not, but it's worth a try):

1)

function reload_div() {
    // Remove all child nodes from div first
    var div = document.getElementById('div_id');
    while (div.firstChild) {
        div.removeChild(div.firstChild);
    }

    document.getElementById('div_id').innerHTML = 'blah blah blah';
}

2)

function reload_div() {
    // Remove the div first
    var parent = document.getElementById('div_id').parentNode;
    parent.removeChild(document.getElementById('div_id'));

    // Recreate the div
    var div = document.createElement('div');
    div.setAttribute('id', 'div_id');

    // Append the div to the parent
    parent.appendChild(div);

    document.getElementById('div_id').innerHTML = 'blah blah blah';
}


来源:https://stackoverflow.com/questions/7218070/reload-contents-of-div-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!