Распространение событий в jQuery с IFrame - PullRequest
1 голос
/ 03 июня 2019

У меня есть html-файл с именем first.html , в котором есть элемент iframe для загрузки другого html-файла с именем second.html .Как мы можем общаться между этими двумя файлами HTML.Я попытался вызвать событие из second.html и поймать то же самое на first.html.Но распространение события не удалось.

Вот файл first.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" /> 
<script>
   function onLoad(){
      alert("onLoad");
      var iframe = $('#iframeID').contents();
      iframe.find("#button").on("SUBMIT",function(){
          // business logic
          alert("Clicked");
      });
   }
</script>
</head>
<body>
   <iframe id="iframeID" onload="onLoad()" height="1000" width="1000" src = './second.html'></iframe>
</body>
</html>

Вот файл second.html file

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" />
    <script>
        function myFunction(){
            $('#button').trigger("SUBMIT");
        };
    </script>
</head>
<body>
    <button id="button" type="button" onclick="myFunction()">Click me</button>
</body>
</html>

1 Ответ

1 голос
/ 04 июня 2019

Вы не можете использовать jquery для связи, потому что пузырьки событий останавливаются в корне документа, а это контейнер iframe и не достигают хост-документа.Вы можете использовать Сообщение для связи.

Попробуйте этот код, он работает.

Вот файл first.html .

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>

 // addEventListener support for IE8
        function bindEvent(element, eventName, eventHandler) {
            if (element.addEventListener){
                element.addEventListener(eventName, eventHandler, false);
            } else if (element.attachEvent) {
                element.attachEvent('on' + eventName, eventHandler);
            }
        }

 // Listen to message from child window
        bindEvent(window, 'message', function (e) {
           alert("Got the message from child");
        });
</script>
<body>
   <iframe   name="iframeID"   height="1000" width="1000" src = './second.html'></iframe>
</body>
</html>

second.html

<!DOCTYPE html>
<html>
<body>
  <head>

<button id="button" type="button" onclick="myFunction()">Click me</button>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"/>
 <script>

    function myFunction(){
    var message = 'Send the message to parent ';
       window.parent.postMessage(message, '*');
     };

 </script>
 </body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...