【问题标题】:create a dynamic url in pug在 pug 中创建一个动态 url
【发布时间】:2020-04-28 00:21:14
【问题描述】:

我声明了一个名为“name”的变量。一旦用户单击表单,它应该调用函数 myFunction 将用户键入的值分配给变量名称。例如,如果用户键入“John”。 url 将是 localhost:5000/profile/John。但我得到 document.getElementById("username") 是未定义的。

-let name = "gg";    
    //- -function enteringName() {
    //-      - name = document.getElementById("username").value;
    //- -};

    <h1>Log in</h1>
    <form action="/profile/#{name}"  method="POST" id="loginForm" onclick="#{myFunction()}" >
      <label for="username">username:</label><br />
      <input type="text" id="username" name="username"/>
      <br />
      <label for="password">password:</label><br />
      <input type="text" id="password" name="password" /><br /><br />
      <input type="submit" value="Log in" />
      <br />
    </form>
    <p>

      <a href="http://localhost:3000/registration">register here</a>
    </p>
    <script>

function myFunction() {
 -name = document.getElementById("username").value;
}
</script>

【问题讨论】:

    标签: javascript pug


    【解决方案1】:

    试试这个。哈巴狗压痕存在一些问题。 pug 也只是服务器渲染 html,但在客户端你应该通过 js 将 name 设置为 element。在 codepen 中测试了这段代码,也看看那里https://codepen.io/aidonline01/pen/rNOwWJY :)

    -let name = "gg";
    //- -function enteringName() {
    //-      - name = document.getElementById("username").value;
    //- -};
    
    <h1>Log in 1</h1>
      <form action="/profile/#{name}"  method="POST" id="loginForm" onclick="myFunction()" >
        <label for="username">username:</label><br />
        <input type="text" id="username" name="username"/>
        <br />
        <label for="password">password:</label><br />
        <input type="text" id="password" name="password" /><br /><br />
        <input type="submit" value="Log in" />
        <br />
      </form>
    <p>
    
    <a href="http://localhost:3000/registration">register here</a>
    </p>
    script
      .
        function myFunction() {
          #{name} = document.getElementById("username").value;
          document.getElementById("loginForm").action = `/profile/${#{name}}`;
        }
    

    【讨论】:

    • 将变量名称从 Pug 传递到客户端 javascript 的值是什么?如果您将#{name} 替换为foo,它的工作原理是一样的。
    • 我不知道,但这不是问题的一部分吗?
    • #{name} 保存我在 name 中存储的值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多