为 iframe 设置 src 属性

我有一个主页(实际上是一个 JSP) ,其中包含一个 iframe;

<iframe name="abc_frame" id="abc_frame" src="about:blank" frameborder="0" scrolling="no"></iframe>

现在主页上有多个链接(通过 JSP 动态呈现) ,它们可以尝试将 src 设置为某个 URL..。

现在我的问题是,使用 jQuery (may be live ()) ,我能否以这样一种方式覆盖它,即 abc _ frame 的“ src”属性总是有一些特定的值(例如“ some fixedURL”)

我无法捕获链接单击,因为它完全是通过一些 Java 代码动态创建的,因此我试图覆盖 iframe src?

189150 次浏览

Use attr

$('#abc_frame').attr('src', url)

This way you can get and set every HTML tag attribute. Note that there is also .prop(). See .prop() vs .attr() about the differences. Short version: .attr() is used for attributes as they are written in HTML source code and .prop() is for all that JavaScript attached to the DOM element.

$(document).ready(function() {
$('#abc_frame').attr('src',url);
})

You cannot set FIX iframe's src or prevent javascript/form submit to change its location. However you can put script to onload of the page and change action of each dynamic link.

if you are using jQuery 1.6 and up, you want to use .prop() rather than .attr():

$('#abc_frame').prop('src', url)

See this question for an explanation of the differences.

While generating the links set the target to the iframes name property and you probably wont have to deal with jquery at all.

<a href="inventory.aspx" target="contentframe"  title="Title Inventory">
<iframe id="iframe1" name="contentframe"  ></iframe>
$(".excel").click(function () {
var t = $(this).closest(".tblGrid").attr("id");
window.frames["Iframe" + t].document.location.href = pagename + "?tbl=" + t;
});

this is what i use, no jquery needed for this. in this particular scenario for each table i have with an excel export icon this forces the iframe attached to that table to load the same page with a variable in the Query String that the page looks for, and if found response writes out a stream with an excel mimetype and includes the data for that table.

Setting src attribute didn't work for me. The iframe didn't display the url.

What worked for me was:

window.open(url, "nameof_iframe");

Hope it helps someone.

<script type="text/javascript">
document.write(
"<iframe id='myframe' src='http://www.example.com/" +
window.location.search + "' height='100' width='100%' >"
)
</script>

This code takes the url-parameters (?a=1&b=2) from the page containing the iframe and attaches them to the base url of the iframe. It works for my purposes.