jquery iframe src

2019-03-03 14:32发布

问题:

I have an HTML page containing an iframe and I am trying to write functions on links in the iframe. The functions will make changes in the HTML page...

The following script works on the first link that is clicked in the iframe. But when the iframe chages "src" the function will not work any more.

How can I make it work even if the src of the iframe is changed?

(all pages are on the same domain)

<script type="text/javascript">
  $("iframe").contents().find("a").click(function() {
    alert('Load was performed.');
  });
</script>

回答1:

try to use the .live() method, it binds an event to the existing elements and future elements. When you change the src, you need to bind again the click event to the new links.

I don't know if the .live() method works on a iframe but you can try this:

  $("iframe").contents().find("a").live('click',function() {
    alert('Load was performed.');
  });

Sorry for my broken english!.

i don't know if it will works (sorry I don't have where to test things now), but what happens if you try to bind an function on the onLoad event of your iframe, (even if W3C says that iframe has no events, it appears to be supported by all browsers):

    <iframe src="/my_contents" onLoad="onload_function()"></iframe>
    ...
   <script>
        onload_function(){
          $(function(){
            $("iframe").contents().find("a").click(function() {
              alert('Load was performed.');
            });
          });
        }
    </script>


回答2:

if its the same as your domain it should work if not Because of Some Origin polciy it will not work as its cross-domain.