正在获取HTML表单之外的值

Getting values outside a HTML form

本文关键字:表单 获取 HTML      更新时间:2023-09-26

在我的content.js中,我正在编写一个新的HTML页面,其中包含var avar b。这两个变量是以前在content.js中创建的,所以我可以很容易地在HTML页面中使用它们。现在,我想在用户完成表单编辑并按下Accept按钮时覆盖这些变量ab。我能做到这一点吗?

这是代码的一部分

  var a="FName";
   var b="LName";
    var myWindow = window.open("Accept", "myWindow", "width=450, height=300");
     myWindow.document.write(

"<html>"+
   "<head>"+
   '<script> function closeWindow(){ var x = document.getElementById("firstname").value alert(x); window.close();}'+
 "</script>"+
 "</head>"+
  "<body>"+   
      "<form>"+
       "<div id=leadinformation>"+
        "<p id=titleParagraph>You are about to create a new Lead:</p>"+
         "First Name....."+ "<input type=text id=firstname value="+a+">" +"<br>"+
         "Last Name....."+ "<input type=text id=lastname value="+b+">" +
        "</div>"+
         "<div>"+
          "<button id=Accept onClick=closeWindow() >Accept</button>"+
          "<button id=Close onClick=closeWindow() >Close</button>"+
        "</div>"+
      "</form>"+
   "</body>"+
  "<html>" 
);
myWindow.document.getElementById('Accept').onclick=Accept;
myWindow.document.getElementById('Close').onclick=Close;
    function Accept(){   
alert(myWindow.document.getElementById('firstname').innerText);
}  
    function Close() {//do smthing 
}

很抱歉格式不正确。

当前是Accept()的输出;目前是空的。如何获得名字输入结果?

我想要实现的目标:1) 我正在页面上创建一个按钮
2) 当我点击按钮时,会弹出一个新的html页面(我正在硬编码的页面)
3) 我使用之前创建的一些变量预先填充表单
4) 当点击表单上的Accept按钮时,Accept()函数会被触发,我想在那里使用用户编写的那些输入值。

这应该会对您有所帮助:共享页面的全局javascript变量(…).

问题是关于"如何将一个变量共享到iframe中的另一个页面",但这也适用于新窗口。

即:

myWindow.document.write(
  "<html>" +
    "<head>" +
      '<script>' +
        'function closeWindow(){' +
          'var x = document.getElementById("firstname").value;' +
          'alert(x);' +
          '// do something to parent.a and parent.b here, just because you can:' +
          'parent.a = "Oh, would you look at it, it works!";' +
          'parent.b = "And it is so pretty too!";' +
          'window.close();' +
        '}' +
      "</script>" +
    "</head>" +
    " Your body code here, etc " +
  "</html>"
);

此外,请注意,在新窗口的JavaScript代码中向var x插入值后,您的代码缺少分号(;)。这很可能会使您的代码出现故障。最后的</html>标签缺少斜杠,但我不知道这是否会破坏任何东西;你最好也把它修好,以防万一。