jQuery on() 事件未针对 sweetalert2 文本框触发
jQuery on() event not firing for sweetalert2 textboxes
我在 sweetalert2 中动态创建了这样的文本框:
swal({
title: 'Enter Info',
showCancelButton: true,
html: "<table>" +
"<tr>" +
"<td>name</td>" +
"<td><input type='text' id='name'/></td>" +
"</tr>"
"<tr>" +
"<td>email</td>" +
"<td><input type='text' id='email'/></td>" +
"</tr>"
"</table>"
}).then(function(){
// ajax
});
和jQuery监听文本框变化事件的函数。
$(document).ready(function () {
<script type="text/javascript">
$('#name').on('change', function(e) {
console.log($(this).val());
});
</script>
});
但是在 sweetalert2 中更改文本框值时不会触发事件。 jQuery 已正确加载,并且适用于 sweetalert2 模型之外的其他文本框。我也尝试在 html:
上面的 </table>
之后添加 <script>...</script>
但仍然没有成功。有人可以帮我吗?任何输入将不胜感激。
将$('#name').on('change', function(e) {
更改为$(document).on('change','#name', function(e) {
- 正确委派活动
发生这种情况是因为您正在使用
$('#name').on('change', function(e) {}); // this works for static dom
$(document).on('change','#name', function(e) {}); // this works for static as well as content dynamically added in dom.
我在 sweetalert2 中动态创建了这样的文本框:
swal({
title: 'Enter Info',
showCancelButton: true,
html: "<table>" +
"<tr>" +
"<td>name</td>" +
"<td><input type='text' id='name'/></td>" +
"</tr>"
"<tr>" +
"<td>email</td>" +
"<td><input type='text' id='email'/></td>" +
"</tr>"
"</table>"
}).then(function(){
// ajax
});
和jQuery监听文本框变化事件的函数。
$(document).ready(function () {
<script type="text/javascript">
$('#name').on('change', function(e) {
console.log($(this).val());
});
</script>
});
但是在 sweetalert2 中更改文本框值时不会触发事件。 jQuery 已正确加载,并且适用于 sweetalert2 模型之外的其他文本框。我也尝试在 html:
上面的 </table>
之后添加 <script>...</script>
但仍然没有成功。有人可以帮我吗?任何输入将不胜感激。
将$('#name').on('change', function(e) {
更改为$(document).on('change','#name', function(e) {
- 正确委派活动
发生这种情况是因为您正在使用
$('#name').on('change', function(e) {}); // this works for static dom
$(document).on('change','#name', function(e) {}); // this works for static as well as content dynamically added in dom.