使用 Jquery 单击元素从新弹出窗口获取值

问题描述 投票:0回答:1

我想通过单击新弹出窗口上的元素的事件来从新弹出窗口中获取值。单击按钮后,我的代码第一次运行。在新的弹出窗口上重新加载页面后,我的代码不起作用。

索引.html

<button id="open-new-windows">TEST</button>

<script>
  $("#open-new-windows").click(function () {
    var w = window.open(
      "http://localhost/test/child.html",
      "TEST",
      "width=300,height=400"
    );

    w.addEventListener("load", function () {
      var html = $(w.document.body).find("ul");
      console.log(html.length); // return 1
      html.on("click", "li", function () {
        var a = $(this).text();
        alert(a);
      });
    });
  });
</script>

Child.html

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
</ul>

我想在页面再次加载后获取一个值。请帮我。谢谢。

javascript jquery popup window
1个回答
0
投票

我的建议是将 LI 的点击侦听器移至 child.html 并使用 Broadcast Channel API:

开始通信

index.html

<button id="open-new-windows">TEST</button>

<script>
    const el = (sel, par = document) => par.querySelector(sel);

    el("#open-new-windows").addEventListener("click", (ev) => {
        const win = window.open(
            "http://localhost:3000/child.html",
            "TEST",
            "width=300,height=400"
        );
    });

    const bc = new BroadcastChannel("comm");
    bc.addEventListener("message", (ev) => {
        // Do nothing if message is not from the expected origin:
        if ( ! /^http:\/\/localhost/.test(ev.origin)) return;
        // All OK: do something with the sent message:
        alert(ev.data);
    });
</script>

child.html

<ul>
    <li>This is LI 1</li>
    <li>This is LI 2</li>
    <li>This is LI 3</li>
    <li>This is LI 4</li>
    <li>This is LI 5</li>
    <li>This is LI 6</li>
    <li>This is LI 7</li>
</ul>

<script>
    const els = (sel, par = document) => par.querySelectorAll(sel);

    const bc = new BroadcastChannel("comm");

    const sendMessage = (ev) => {
        const elLI = ev.currentTarget;
        const text = elLI.textContent;
        bc.postMessage( text );
    };

    els("ul li").forEach(elLI => elLI.addEventListener("click", sendMessage) );
</script>

PS:修复上面的

http://localhost:3000/child.html
以匹配您的配置。

© www.soinside.com 2019 - 2024. All rights reserved.