jquery - 从模板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
值?
解决方案
将这些元素包装在一个容器中,以便您可以保持实例隔离并添加一些类,以便在新容器实例中更轻松地查找元素
请注意,您不能重复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()
});
推荐阅读
- python - python的复利结果不正确
- python - Jupyter notebook _ 我正在尝试导入我的笔记本并遇到此错误。有任何想法吗?
- javascript - 函数内部的 clearInterval 没有清除,当函数被调用并且执行其他函数后反应状态发生变化时
- python - 在python中将tiff文件合并为一个tiff文件(合并的tiff应该有n页)
- python - 面向对象的 Python 问题
- api - 如何检索 VM 是关闭还是打开?
- javascript - 为什么 CSS Grid 行不起作用?这是我的问题
- javascript - React 中只运行一次的功能组件
- python - 将列表变量名转换为键,将其值转换为python中字典的值
- python - 我对 Python 代码有疑问。执行代码时条目显示 [*]