Google chrome extension Google chrome在表单中传递字段值

Google chrome extension Google chrome在表单中传递字段值,google-chrome-extension,Google Chrome Extension,My popup.html: <!doctype html> <html> <head> <form name="orderform"> First name: <input type="text" name="firstname" /><br /> Last name: <input type="text" name="lastname" /> <INPUT TYPE="button" N

My popup.html:

<!doctype html>
<html>
  <head>
      <form name="orderform">
First name: <input type="text" name="firstname" /><br />
Last name: <input type="text" name="lastname" />
<INPUT TYPE="button" NAME="button1" Value="Read" onClick="readText(this.form)">

</form> 
<!-- JavaScript and HTML must be in separate files for security. -->
    <script src="popup.js"></script>
  </head>
  <body>
  </body>
</html>
不幸的是,上面的代码没有打印名字的值。有人能告诉我我做错了什么吗

  • 您的表单位于
    部分;在体内移动它
  • 不要使用
    form.field
    ,请将DOM
    id
    属性与
    document.getElementById()
    结合使用
  • 使用
    var
    定义局部变量;像这样:

    First name: <input type="text" id="firstname" /><!-- note the use of id=... -->
    <script type="text/javascript"> 
        var TestVar = document.getElementById('firstname').value;
    </script>
    
    popup.js

    function readText(){
        var TestVar = document.getElementById('firstname').value;
        console.log(TestVar); alert(TestVar);
        chrome.tabs.create({"url":"http://www.google.co.in","selected":true}, function(tab){  });
    }
    

    首先,您的控制台调用中有一个错误的引号:
    console.log(TestVar”);
    谢谢您指出它。当我复制并粘贴它时,我犯了一个错误。我将编辑它。
    <html>
    <head>
    <script src="popup.js"></script>
    </head>
    <body>
    <form name="orderform">
        First name:
        <input type="text" name="firstname" id="firstname" />
        <br />
        Last name:
        <input type="text" name="lastname" id="lastname" />
        <input type="button" name="button1" value="Read" onclick="readText()">
    </form>
    </body>
    </html>
    
    function readText(){
        var TestVar = document.getElementById('firstname').value;
        console.log(TestVar); alert(TestVar);
        chrome.tabs.create({"url":"http://www.google.co.in","selected":true}, function(tab){  });
    }