没有为表单元格激发jQuery模糊事件

jQuery blur event not fired for table cell

本文关键字:jQuery 模糊 事件 单元格 表单      更新时间:2023-09-26

我正在使用jQuery ajax动态加载一个表,该表的行具有"contenteditable=true",我正在尝试侦听每个单元格的模糊事件,以便它触发一个函数来动态更新该单元格。问题是事件模糊根本没有启动,我尝试过不同的选择器(表、tbody,最后是整个文档),但都是徒劳的。

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src='jquery-1.8.3.js'></script>
    <link rel="stylesheet" href='jquery-ui-1.8.7.custom.css' type="text/css">
        <?php
        include './datatable_include.php';
        ?>
        <script type="text/javascript">
            $(function () {
                $.ajax({//create an ajax request to load_page.php
                    type: "GET",
                    url: "load_table.php",
                    dataType: "html", //expect html to be returned                
                    success: function (response) {
                        $('#dataTable').find('tbody').html(response);
                        initDataTable('#dataTable', null);
                    }
                });
            });

            $(document).bind("blur", "td", (function () {
                // this code isn't reached 
                alert("ahoo");
                var id = $(this).attr("id");
                var name = $(this).attr("name");
                var message_status = $("#status");
                var value = $(this).text();
                $.post('update_table.php', "id=" + id + "&" + name + "=" + value, function (data) {
                    if (data != '')
                    {
                        message_status.show();
                        message_status.text(data);
                        //hide the message
                        setTimeout(function () {
                            message_status.hide()
                        }, 3000);
                    }
                });

            }));

        </script>
    </head>
    <body>
        <table id="dataTable" width="700px" >
            <thead>
                <tr>    
                    <th>Name</th>
                    <th>ID</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </body>
</html>

尝试

 $(document).bind("td").blur(function()
 {
 });

表td似乎不是一个标准的可聚焦元素,所以不能模糊它。尝试将tabsindex属性添加到每个td

<td tabindex="1">focus on me</td>

绑定函数的定义如下:

.bind( eventType [, eventData ], handler )

所以,你应该这样做:

 $('td').bind('blur', function(){
   //event handler statement goes here
 });

正如@paul roub在上面的评论中提到的,您应该使用live()函数,因为您正在动态创建td元素。

$('td').live('blur', function(){
 //event handler statement goes here
});