is there simple expression to access iframe body using jq开发者_开发知识库uery. assume iframe's id is theframe.
I want to give event handler to iframe. for example,
$("#theframe").contents().find("body").click(function() {
alert("hello, you touched me~");
});
but, this code doesn't work in IE.
any alternative idea help me~
Give a name property for the iframe element. Now you can reference it like this:
window.name_of_iframe
Your iframe may not have jQuery so, using standard traversing is a safer way
iframe_body = window.name_of_iframe.document.getElementsByTagName("body")[0];
This will be the body element in the iframe. This is however usable by jQuery on the host page, so:
$(window.name_of_iframe.document.getElementsByTagName("body")[0]);
is your jQuery wrapper for the iframe's body element.
Be careful to do this only if the iframe is loaded:
$("iframe[name=name_of_iframe]").load(function() {
var iframe_body = window.name_of_iframe.document.getElementsByTagName("body")[0];
$(iframe_body).click(function() {
alert("hello, you touched me~");
});
});
UPDATE: tested it in IE, and there is a rather starnge behaviour with it. In firefox you have to wrap it inside a document ready event, but in IE, it has to be outside, right after the iframe element. This version works in IE and Firefox too.
<iframe name="ifr" src="?if=1"></iframe>
<script type="text/javascript">
var ifr_loaded = false;
$("iframe").load(function() {
$(window.ifr.document.getElementsByTagName("body")[0]).click(function() { alert("s"); });
ifr_loaded = true;
});
$(function() {
if (!ifr_loaded)
{
$("iframe").load(function() {
$(window.ifr.document.getElementsByTagName("body")[0]).click(function() { alert("d"); });
});
}
});
</script>
UPDATE 2: a shorter version, but it has its drawback, that you have to specify the source of the iframe in the javascript, but it works in all browsers I tried.
<iframe name="ifr"></iframe>
<script type="text/javascript">
$(function() {
$("iframe").load(function() {
$(window.ifr.document.getElementsByTagName("body")[0]).click(function() { alert("d"); });
}).attr("src","/teszt/v/index.php?if=1");
});
</script>
UPDATE 3: And an even simpler way for the end:
<script type="text/javascript">
function init_iframe(obj) {
$(obj.document.getElementsByTagName("body")[0]).click(function() { alert("d"); });
}
</script>
<iframe name="ifr" src="?if=1" onload="init_iframe(window.ifr);"></iframe>
精彩评论