我想从一个新的弹出窗口中通过事件点击一个新的弹出窗口中的元素获得价值.我的代码在我点击按钮后第一次工作.在我重新载入新的弹出窗口页面后,我的代码不工作.

Index.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>

enter image description here

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

推荐答案

我的建议是将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) => {
        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>

This way, even if you refresh the child.html page, it will attach again to the same broadcasting channel.
See here for another example

PS:
edit the above's http://localhost:3000/child.html to match your configuration.

Javascript相关问答推荐

如何在JavaScript中通过一次单击即可举办多个活动

如何才能拥有在jQuery终端中执行命令的链接?

如果Arrow函数返回函数,而不是为useEffect返回NULL,则会出现错误

您能在卸载程序(QtInsteller框架)上添加WizardPage吗?

如何将数组用作复合函数参数?

如何在箭头函数中引入or子句?

如何使用基于promise (非事件emits 器)的方法来传输数据?

是否可以将Select()和Sample()与Mongoose结合使用?

将多个文本框中的输出合并到一个文本框中

如何根据输入数量正确显示alert ?

为什么我看到的是回复,而不是我的文档?

我的NavLink活动类在REACT-ROUTER-V6中出现问题

如何压缩图像并将其编码为文本?

P5play SecurityError:无法从';窗口';读取命名属性';Add';:阻止具有源的帧访问跨源帧

在高位图中显示每个y轴系列的多个值

如何在Reaction中设置缺省值, Select 下拉列表,动态追加剩余值?

Played link-Initialize.js永远显示加载符号

在此div中添加一个类,并在一段时间后在Java脚本中将其删除

使用Java脚本在div中创建新的span标记

react :图表负片区域不同 colored颜色