从 #each 输入列表中获取特定用户

get specific user from list of #each input

我使用 {{#each}} 将用户显示为 input type=button 的列表,然后当点击功能将 运行 获取该输入的值但我得到未定义的。

代码如下:

app.js

app.get('/search',(req,res)=>{

    data.find({}).then(data=>{

        res.render('./search', {data: data});

    });

search.handlebars

     <table class="blueTable" >
            <thead>
             <tr> 
                <th>Name</th>
             </tr>
            </thead>

            <tbody>
        {{#each data}}
                <tr> 
                    <td>       

                        <input class="button" type="button" onclick="recive()"  id="reciver" name="reciver" value="{{Name}}">
                    </td>

                 </tr>

            {{/each}}

            </tbody>
            </table>

         <script>
              function recive(){
                 var reciver = document.getElementById("reciver").value
                 console.log(reciver)
              }
         </script>

为什么在 Javascript 中未定义?

undefined is a property of the global object; i.e., it is a variable in global scope. The initial value of undefined is the primitive value undefined . ... A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value.

基本上它不能引用我假设的 {{Name}} 部分。 将{{Name}}更改为{{this}}

如果您有一个名为 People 的对象

{
  people: [
    "Yehuda Katz",
    "Alan Johnson",
    "Charles Jolley"
  ]
}

注意{{#each people}},然后将{{Name}}更改为{{this}}

<ul class="people_list">
      {{#each people}}
        <li>{{this}}</li>
      {{/each}}
</ul>

输出:

<ul class="people_list">
  <li>Yehuda Katz</li>
  <li>Alan Johnson</li>
  <li>Charles Jolley</li>
</ul>

当循环遍历每个项目时,您可以选择通过 {{@index}}

引用当前循环索引
{{#each array}}
      {{@index}}: {{this}}
{{/each}}

此外,对于对象迭代,{{@key}} 引用当前键名:

{{#each object}}
  {{@key}}: {{this}}
{{/each}}
     <table class="blueTable" >
        <thead>
         <tr> 
            <th>Name</th>
         </tr>
        </thead>

        <tbody>
    {{#each data}}
            <tr> 
                <td>       
                    <input class="button" type="button" onclick="receive(this)" name="reciver" value="{{Name}}">
                </td>

             </tr>

        {{/each}}

        </tbody>
        </table>

     <script>
          function receive(element){
             var receiver = element.value
             console.log(receiver)
          }
     </script>