简体   繁体   English

如何在“名字”形式与我的函数之间建立联系?

[英]How to connect between the form “firstname” to my function?

I'm new to JS and I practice, I want to connect between my form "firstname" to my function so when someone will click the button it will change the headline to "Hello ____ (his name)". 我是JS的新手,我想在表单“名字”和函数之间建立联系,以便当有人单击按钮时,它将标题更改为“ Hello ____(他的名字)”。 I can't understand what should I add and where to my code so it will work. 我不明白我应该添加什么以及代码的位置,以便它可以正常工作。 Thanks for your help. 谢谢你的帮助。

 <h1 class="example"> My Application </h1>

       <body>
       <form action="/action_page.php">
        First name:<br>
        <input type="text" name="firstname" value="" >
        <br>
        Last name:<br>
        <input type="text" name="lastname" value="">
        <br><br>
        <input type="submit" value="Submit">
      </form> 

      <button onclick="Hello(name)">Click here to change headline</button>

`<script>`
function hello(name){
    return document.querySelector(".example").innerHTML = "Hello" + name ;
}     

</script>

There's a few small issues in your code, but you were close. 您的代码中有一些小问题,但是您已经接近了。 You're not passing anything into the function, you just have to get the values from your form. 您无需向函数传递任何内容,只需从表单中获取值即可。 There are several ways to do this, but without overly complicating what you already have or understand, here's a working version. 有几种方法可以做到这一点,但又不会过度复杂化已有或理解的内容,这是一个有效的版本。

  <h1 class="example"> My Application </h1>
   <form action="/action_page.php">
      First name:<br>
      <input type="text" id="firstName" name="firstname" value="" >
      <br>
      Last name:<br>
      <input type="text" name="lastname" value="">
      <br><br>
      <input type="submit" value="Submit">
  </form> 

  <button onclick="Hello()">Click here to change headline</button>

<script>
   function Hello(){
      var name = document.getElementById("firstName").value;
      document.querySelector(".example").innerHTML = "Hello " + name ;
   }     
</script>

Notice the addition of the 'id="firstName"' attribute to your input. 请注意,在您的输入中添加了'id =“ firstName”'属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM