使用Javascript(或jQuery)加载iframe内容

Load iframe content with Javascript (or jQuery)

本文关键字:加载 iframe 内容 jQuery Javascript 使用      更新时间:2023-09-26

我需要通过html文件的同一文件夹中的文件读取外部代码。问题是HTML没有在服务器上运行,所以我不能使用jQueryload()和其他解决方案。所以我认为通过这样的iframe加载代码:

<iframe id="iframe" src="script1.html"></iframe>

文件中的文本如下:

One paragraph. Some words
Other paragraph, and more words...

我需要获取句子并放入数组,但我甚至无法通过jQuery获取文本。我正在尝试这样做:

var text = $("#iframe").val();

但它什么也没做,所以我尝试在文件中插入html标签:

$('#iframe').contents().find("html").html();

什么也没有。那么,怎么做呢?

您是否尝试过使用简单的$.ajaxpost/get调用?ajax将处理任何JS&script1.HTML 中的HTML

有点像:

$.ajax({ type: "POST", url:"script1.html", dataType:"html", success: function(data) { // do what you want here }});

Baptiste

您可以通过以下方式获得您的价值:

 var iBody = $("#iframe").contents().find("body");
//here you have the control over your element (#myContent)
var myContent = iBody.find("#myContent"); //store it in variable here where myContent is the div id you want to get value of..