1

我的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>

popup.js

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

不幸的是,上面的代码没有打印名字的值。有人可以告诉我我在这里做错了什么。

4

1 回答 1

0
  1. 您的表格在该<head>部分中;在体内移动
  2. 不要使用form.field,将 DOMid属性与document.getElementById().
  3. 用于var定义局部变量;像这样:

    First name: <input type="text" id="firstname" /><!-- note the use of id=... -->
    <script type="text/javascript"> 
        var TestVar = document.getElementById('firstname').value;
    </script>
    
  4. 用于alert()字符串和数字

这是完整的代码:

popup.html

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

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){  });
}
于 2012-06-02T12:28:12.650 回答