首页 > 解决方案 > 从模板jQuery获取输入值

问题描述

我有一个模板

<div id="template" style="display: none;">
  <strong>Name</strong>: <span class="name"></span><br/>
  <input type="number" id="amount">  
  <button type="button" onclick="App.submit()">submit</button>         
</div>

可用于生成多个 div

 for (var i = 0; i < 5; i++) {  
   var list = $('#list');
   var template = $('#template');
   template.find('.name').text(i); 
   list.append(template.html());         
 }

从其中一个 div 中单击提交按钮时,如何获取其name和输入的amount值?

标签: jqueryhtml

解决方案


将这些元素包装在一个容器中,以便您可以保持实例隔离并添加一些类,以便在新容器实例中更轻松地查找元素

请注意,您不能重复id=amount,因为 id 必须是唯一的。

然后委托一个点击监听器而不是使用onclick

HTML

<div id="template" style="display: none;">
  <div class="input-row">
    <strong>Name</strong>: <span class="name"></span><br/>
    <input type="number" class="amount">
    <button type="button" class="row-submit" >submit</button>
  </div>
</div>

JS

$(document).on('click', 'button.row-submit', function(){
    // the new row wrapper
    var $row = $(this).closest('.input-row'),
        // find the elements within this row instance
        name = $row.find('.name').text(),
        amount = $row.find('.amount').val();

        // do something with the values            

        // then do your app submit
        App.submit()

});

推荐阅读