将HTML表单传递给Javascript(ECMAScript)对象

时间:2015-08-24 17:22:43

标签: javascript html5 html-form

嗨,这是我创建的代码,但它不起作用:

  <P>Enter the details below to create a person object:</P>
    <label for ="fName" class="ui-input-text-label"><span style="font weight:bold;">First Name</span><span style="color: #82c341;"> </span></label>
    <input type="text" class="fName" name="fName" value="" placeholder="First Name">
    <label for ="sName" class="ui-input-text-label"><span style="font weight:bold;">Surname</span><span style="color: #82c341;"> </span></label>
    <input type="text" class="sName" name="sName" value="" placeholder="Surname">
    <label for ="age" class="ui-input-text-label"><span style="font weight:bold;">Age</span><span style="color: #82c341;"> </span></label>
    <input type="number" class="age" name="age" value="" placeholder="Age">
    <button class="submit" onClick="createPerson(this.form)">Submit</button>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/pages.js"></script>
<script type="text/javascript" src="js/util.js"></script>
<script>
    createPerson(){
        firstName=fName;
        surName=sName;
        age=this.age;
        console.log(firstName);
        console.log(surName);
        console.log(age);
        }
</script>

console.log&只是作为测试。

1 个答案:

答案 0 :(得分:0)

像这样的东西,也许:

<form name="personForm">
  <P>Enter the details below to create a person object:</P>

  <label for ="fName" class="ui-input-text-label"><span style="font weight:bold;">First Name</span><span style="color: #82c341;"> </span></label>
  <input type="text" class="fName" name="fName" value="" placeholder="First Name">
  <label for ="sName" class="ui-input-text-label"><span style="font weight:bold;">Surname</span><span style="color: #82c341;"> </span></label>
  <input type="text" class="sName" name="sName" value="" placeholder="Surname">
  <label for ="age" class="ui-input-text-label"><span style="font weight:bold;">Age</span><span style="color: #82c341;"> </span></label>
  <input type="number" class="age" name="age" value="" placeholder="Age">
  <button class="submit">Submit</button>
</form>

<script>
  var Person = function(firstName, surName, age){
    this.firstName = firstName;
    this.surName = surName;
    this.age = age;
  }

  document.querySelector("button").addEventListener("click", function(e){
    e.preventDefault();
    var f = document.forms[0];
    var person = new Person(f.fName.value, f.sName.value, f.age.value);
    console.log(person);
  });
</script>

不确定这有多大意义。取决于你的背景。