Iframe without src but still has content?

2019-01-14 05:50发布

问题:

While debugging jquery code on their site ( via chrome developer toolbar)

I noticed that their examples are given under Iframe :

Here - for example there is a sample which is under an Iframe but after investigating , I see that the Iframe doesn't have SRC

The picture shows it all

Question :

Is it possible to set content to an Iframe without setting its SRC ?

p.s. this menu also shows me an empty content

回答1:

Yes, it is possible to load an empty <iframe> (with no src specified) and later apply content to it using script.

See: http://api.jquery.com/jquery-wp-content/themes/jquery/js/main.js (line 54 and below).

Or simply try:

<iframe></iframe>

document.querySelector('iframe')[0]
        .contentDocument.write("<h1>Injected from parent frame</h1>")


回答2:

Yes, Here is how you change the html of the iframe with jQuery

var context = $('iframe')[0].contentWindow.document,
    $body = $('body', context);
$body.html('Cool');

Demo: http://jsfiddle.net/yBmBa/

document.contentWindow: https://developer.mozilla.org/en-US/d...



回答3:

Looks like this is the most compatible solution across browsers and also it is recognized by the W3C

<iframe src="about:blank"></iframe>


回答4:

Sure. You can get a reference to the iframe's document object with

var doc = iframe.contentDocument;

and then you can create and add elements like you do in the current document.

If the iframe doesn't have a src attribute, it will still contain an empty document. I believe though that at least older IE versions require the src attribute to be set, otherwise the iframe won't have a document.

See also: contentDocument for an iframe.



回答5:

Try giving :

src ="javascript:false;"


回答6:

Mixing best answers in javascript and jQuery, I come up with this solution for each iframe in a page:

<div class="iframewrapper ws-s-top mb-50" data-content="<!DOCTYPE html><html><head></head><body><p>Hello world</p></body></html>">
    <iframe frameborder="0" src=""></iframe>
</div>

$(".iframewrapper").each(function(){
    var html = $(this).attr("data-content");
    var iframe = $(this).find('iframe');
    var context = iframe[0].contentDocument.write(html);
    iframe[0].contentWindow.document.close(); //without this line, page loading animations won't go away!
});