为什么在同一类中触发点击事件时不触发更改事件

why change event is not triggered while click event is triggered in same class?

本文关键字:事件 一类 为什么      更新时间:2023-09-26

嗨,我有使用 jquery 移动版创建移动应用程序的代码。BUt 在我的代码中,我动态创建了页面并计算了员工经验。由于 id 在新创建的行上生成,因此我将类视为唯一来触发事件。但是,当点击事件在同一类"to"上触发时,不会触发该更改事件。下面是我的代码。请建议如何实现这一目标?

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
    <link href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/v0.1.1/jquery.mobile.datepicker.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
    <script src="https://rawgithub.com/jquery/jquery-ui/1.10.4/ui/jquery.ui.datepicker.js"></script>
    <script id="mobile-datepicker" src="https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/v0.1.1/jquery.mobile.datepicker.js"></script>
    <!-- Page Values and Script -->
    <script>
    $(document).ready(function() {
        $("input.add").live('click', function() {
            var length = 0;
            var table = $(this).closest('table').attr('id');
            if (table == 'Employee')
                var length = $('#Employee').find('tr').length;
            console.log(length);
            var $tr = $(this).closest('tr');
            var $clone = $tr.clone();
            $clone.find('input:text').val('');
                       
            var id2 = 'To' + length;
            console.log(id2);
            $clone.find(".to").parent().html(' <input class="to" id="' + id2 + '" name="To" type="text" value="" data-role="date" style="width:100%" />');
            $clone.find('input[data-role="date"]').date();
            console.log($clone);
            $tr.after($clone);
        });
        

尝试更改此代码

 $('input.to').on('change', function(){...});

 $(document).on('change','input.to', function(){...});

我假设您使用的是jquery.1.7版本。因此,请尝试使用如下所示的.live

$('input.to').live('change', function() {

或者,如果是动态添加的元素,最好使用$(document)来侦听动态添加元素的事件

$(document).on('change','input.to', function() {