Dynamic Elements are not appearing in IE8 until th

2019-01-24 06:04发布

问题:

I have an Ajax request that returns search results, and I am dynamically creating DOM elements to display those results. This is working as expected in all the browsers I've tested except for IE8.

The request is returning fine, the JavaScript is running successfully, and the elements are being created, but the elements are not being displayed in the page. They only appear after a mouse-click somewhere on the page.

I ran a quick test that ran the callback code without the Ajax request, and it behaved as expected there. So I'm wondering if this has something to do with the way IE8 is managing the callback thread. Has anyone else seen behavior like this, or have insight on it?

The callback is fundamentally very simple. I have reproduced with this:

function catchResults(response) {
    var contentBlock = document.getElementById('divResults');
    var divResults = document.createElement('div');
    var txt = document.createTextNode("Results");
    divResults.appendChild(txt);
    contentBlock.appendChild(divResults);
}

I am using JQuery.ajax to make the call. I have seen the proper behavior in FireFox and Chrome.

Thanks for the help!

回答1:

I ran into this problem not so long ago on IE8.

I think this might be a problem with IE8 not re-rendering the elements in question. An easy way to confirm this is to add a class to the parent element and then remove it. This should trigger IE8 to re-render the element.

If contentBlock is the parent element then you could test with the following:

Javascript version:

// Variable storing the test class name
var testClass = "testClass";
// Add test class to element
contentBlock.className += " "+testClass;
// Remove test class from element
var reg = new RegExp('(\\s|^)'+testClass+'(\\s|$)');
contentBlock.className=contentBlock.className.replace(reg,' ');

jQuery version:

// Variable storing the test class name
var testClass = "testClass";
// Add test class to element and then remove it 
$('#divResults').addClass(testClass).removeClass(testClass);

Just put it at end of the function after you appendChild. Hopefully this should fix your issue.

Reference: http://www.openjs.com/scripts/dom/class_manipulation.php