【问题标题】:How to take form information entered into an info array, and print out that array to a paragraph?如何将表单信息输入到信息数组中,并将该数组打印到段落中?
【发布时间】:2021-07-21 21:33:05
【问题描述】:

我正在尝试获取表单信息,将它们输入到信息数组中,然后将该数组打印到字符串连接中的段落中。

这是我的 HTML:

<body>
   <input type="text" id="name" placeholder="Enter first name">
   <input type="text" id="lName" placeholder="Enter last name">
   <input type="text" id="age" placeholder="Enter age">
   <input type="text" id="email" placeholder="Enter email address">
   <button>Add Info</button>
   <article>
      <div>
         <p>8</p>
      </div>
   </article>
   <p id="future"></p>
   <main>
</body>

这是我的 Javascript:

const btn = document.querySelector('button');
const paras = document.querySelectorAll('p');

    btn.addEventListener("click", function(){
      const name = document.getElementById("#name");
      const lName = document.querySelector("#lname");
      const age = document.querySelector("#age");
      const email = document.querySelector("#email");
      let info = [name + " " + lName + " , you are " + age + "!" + " But by your next birthday, you will 
      inherit $10 million dollars! We will email you your fortune to: " + email + "."];
      document.querySelector("#future").innerHTML = info;})

我明白了:

null [object HTMLInputElement] ,你是[object HTMLInputElement]!但到你的下一个生日,你将继承 1000 万美元!我们会将您的财富通过电子邮件发送至:null。

【问题讨论】:

    标签: javascript html arrays concatenation paragraph


    【解决方案1】:

    有几个问题:

    1. getElementById 只需要 id 作为参数,没有 #。 (querySelector 需要这个,因为它需要一个 css-selector 作为参数)。
    2. 此选择器中有错字:const lName = document.querySelector("#lname")#lName 而不是 #lname
    3. 您打印的是输入元素,而不是它们的值。为此请使用 .value

    const btn = document.querySelector('button');
    const paras = document.querySelectorAll('p');
    
    btn.addEventListener("click", function() {
      const name = document.getElementById("name");
      const lName = document.querySelector("#lName");
      const age = document.querySelector("#age");
      const email = document.querySelector("#email");
      let info = [name.value + " " + lName.value + " , you are " + age.value + "!" + " But by your next birthday, you will inherit $10 million dollars!We will email you your fortune to: " + email.value + "."];
      document.querySelector("#future").innerHTML = info;
    })
    <body>
      <input type="text" id="name" placeholder="Enter first name">
      <input type="text" id="lName" placeholder="Enter last name">
      <input type="text" id="age" placeholder="Enter age">
      <input type="text" id="email" placeholder="Enter email address">
      <button>Add Info</button>
    
      <article>
        <div>
          <p>8</p>
        </div>
      </article>
      <p id="future"></p>
    
    </body>

    【讨论】:

    • 你在帮助别人骗人吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多