首页 > jq的content()方法获取iframe里的内容,语法都对,但是就是没效果

jq的content()方法获取iframe里的内容,语法都对,但是就是没效果

下面是a.html里的内容

<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>


<div  id="wrap">
<iframe id="aaa"  src="b.html" ></iframe>
</div>

<!--w98-->



<script>
$(document).ready(function() {
$('#wrap').contents().find('.bb').html('给我变');
$('#aaa').contents().find('.bb').html('给我变');
$('#wrap').contents().find('#bb').html('给我变');
$('#aaa').contents().find('#bb').html('给我变');
});
</script>


下面是b.html里的内容

<div id="bb" class="bb" >来修改我啊</div>

问题就是我刷新a.html后,显示的文字还是“来修改我啊”,而不是“给我变”
求教这是为什么?


如楼上所说:

<button id="click">click</button>

<script>
$(document).ready(function() {
    $('#click').click(function () {
        //$('#aaa').contents().find('.bb').html('给我变'); //二者皆可
        $('#aaa').contents().find('#bb').html('给我变');
    });

});
</script>

加上一个事件,如click,就变了。。


确实如楼上所说是iframe未加载加载完造成,这点你可以在ready的回调里加入

console.log($('#aaa').contents().find('#bb').length) //0

可以看到
解决办法,是注册一个iframe的loaded响应函数,等iframe加载完在改变

$('#aaa').load(function(){
    $('#aaa').contents().find('#bb').html('给我变');
})

还有问题,可以留言


在jQuery中,$(document).ready()意思是页面结构加载完成之后就开始执行,并不是在页面元素加载完成才执行的,这点要与原生js中的onload函数区分开,所以你iframe里的内容还没有加载出来之后,js就已经运行了,当然不会有显示了


iframe加载的是一整个页面,你直接把js写在b.html里面不就行了


你写个按钮触发这个事件,不要让他自己去触发,你触发的时候也许框架里面的页面还没加载完呢。


可以把你的document.ready改成$(window).on("load", function() {})

【热门文章】
【热门文章】