iframe contents change event?

2019-01-14 15:26发布

问题:

How can I detect when the iframe content has changed and do something upon that change pseudo code below

 $('#waframe').contents().change(function(){
   //do stuff
  });

回答1:

Well, the browser seems to generate a "load" event on an <iframe> element in the context of the containing page. The "load" fires when the "src" is changed; not sure whether it fires when the iframe changes itself.

edit: yes it does seem to fire when the page reloads "internally"

Thus you might try:

$('iframe#yourId').load(function() {
  alert("the iframe has been loaded");
});


回答2:

Am doing a litle trick (dirt but it works) :) to display a loading object

function changeDet(old){ //detect src changes
    if($("iframe#ifID").attr('src') != old){
        $("iframe#ifID").width(0); //error if i hide ...?
    }

    setTimeout('changeDet("' + $("#db").attr('src') + '")',10);
}

var df = $('#iframe#ifID');

df.load(function(){ //content loaded
setTimeout('$("#db").width(var_default_width);',100);
});

changeDet();

$(function(){   
    //jq stuffs...
})
</script>


回答3:

You can use this to fire event on change.. Works on IE8 and firefox

if(document.addEventListener){
    yourIFrameObject.contentWindow.document.addEventListener('keyup', yourFunction, false);
   // window.frames[0].document.addEventListener('keyup', yourFunction, false);
}
else{
//for IE8
    yourIFrameObject.contentWindow.document.attachEvent('onkeyup', yourFunction);
}

You could use a mouseup statement if necessary



标签: jquery iframe