jQuery的on()事件未能为sweetalert2文本框触发

4

我在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>,但仍然没有运气。请问有人可以帮我吗?任何输入都将不胜感激。


2
$('#name').on('change', function(e) { 改为 $(document).on('change','#name', function(e) { - guradio
@guradio,它能用了!非常感谢您的快速回复。您是否愿意将此发布在答案中,以便我可以接受? - Min Naing Oo
当然,我会发布它 - guradio
2个回答

6

$('#name').on('change', function(e) {更改为$(document).on('change','#name', function(e) {

  1. 适当委托事件

3
这种情况发生是因为您正在使用:
$('#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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接