给input赋值的问题

<form name="favform" action="javascript:void(0)" onsubmit="return gotofav(this)">
<input type="txt" name="fav1" value="-1.933227,115.807851"><input type="submit" value="go" /></form>

<form name="favform" action="javascript:void(0)" onsubmit="return gotofav(this)">
<input type="txt" name="fav2" value="-1.933227,115.807851"><input type="submit" value="go" /></form>

<form name="favform" action="javascript:void(0)" onsubmit="return gotofav(this)">
<input type="txt" name="fav3" value="-1.933227,115.807851"><input type="submit" value="go" /></form>

document.getElementById("这里应该怎么写").value =`${newLatLng.lng},${newLatLng.lng}`;

多个表单,一个函数,需要给input赋值。该怎样做呢?谢谢老师。

阅读 1.6k
1 个回答

可以参考下这个,点击一个表单中的go后,只给给该表单内的input赋值

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <form
      name="favform"
      action="javascript:void(0)"
      onsubmit="return gotofav(this)"
    >
      <input type="text" name="fav1" value="-1.933227,115.807851" /><input
        type="submit"
        value="go"
      />
    </form>

    <form
      name="favform"
      action="javascript:void(0)"
      onsubmit="return gotofav(this)"
    >
      <input type="text" name="fav2" value="-1.933227,115.807851" /><input
        type="submit"
        value="go"
      />
    </form>

    <form
      name="favform"
      action="javascript:void(0)"
      onsubmit="return gotofav(this)"
    >
      <input type="text" name="fav3" value="-1.933227,115.807851" /><input
        type="submit"
        value="go"
      />
    </form>

    <script>
      /**
       * 由于onsubmit调用时你传入了this,而onsubmit函数的this就是对应的form
       * 所以我们可以直接从gotofav的参数中获取form,进而执行响应的操作
       * **/
      const gotofav = (form) => {
        if (!form) return

        Array.from(form.querySelectorAll('[type="text"]')).forEach((input) => {
          input.value = 'newValue'
        })
      }
    </script>
  </body>
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题