Setting content of iframe using javascript fails i

2019-08-10 05:45发布

问题:

I'm trying to set the content of a iframe using javascript.

I've the html string. And I'm writing:-

 var iframe = $('iframe')[0],
 content = '<div>test</div>';        
 $(iframe).contents().find('html').html(content);

It works fine in google chrome, but in firefox is shows the content for a moment and the disappears. Please help me to fix it.

回答1:

I faced the same problem. I saw the load function of iframe fires in firefox but not in chrome. So firefox reload the iframe again on load event.

So with your existing code try this:-

   $(iframe).load(function(e){
      $(iframe).contents().find('html').html(content);

    })