jQuery的不工作与动态创建的表 [英] Jquery not working with dynamically created table

查看:161
本文介绍了jQuery的不工作与动态创建的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用jQuery的模板插件动态加载数据到使用在页面加载一个JSON调用表的简单的网页。在该表中,我希望把按钮/ DIV或任何可点击的,我可以再放入一个函数,将打开一个新页面编辑该列的内容。

I have a simple webpage that uses the jquery template plugin to dynamically load data into a table using a json call on page load. In that table, I want to put buttons/div or anything clickable that I can then put a function on that will open a new page to edit the contents of that column.

现在的问题是,没有任何的jQuery的东西的作品中,我放在桌子上的按钮。如果我把相同的按钮出表(即不动态生成它),那么它工作正常,但我不明白每列一个按钮。

The problem is that none of the jquery stuff works in the buttons that I put in the table. If i put the same button out of the table (i.e. do not dynamically generate it) then it works fine but then I dont get one button per column.

下面是我对页面加载

$(document).ready(function() {
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: "http://server:8000/categories/list",
        success: function (data) {
                LoadCategories(data['CategoryList']);
        }
    });

    $(".editButton").button(); // using jquery-ui
    $(".editButton").click( function() {
        alert("Button has been clicked");
    });
});

和我的模板看起来像

   <script id="catTemplate" type="text/x-jquery-tmpl">  
        <tr id="$CategoryId">  
            <td> <button id="edit-${CategoryId}" class="editButton"> Edit</button> </td>
            <td> ${CategoryName}</td>
            <td> ${OtherValue} </td>
        </tr>  
    </script>  

表正确加载和一切,它只是jQuery的东西是不是适用于动态生成的东西。为什么会这样,我怎么能得到的按钮做我想要什么?

The table loads properly and everything, its just that the jquery stuff is not applied to the dynamically generated stuff. Why is that and how can I get the buttons to do what I want?

推荐答案

您jQuery来添加单击处理程序可能运行前的内容实际上是在页面中。请记住,Ajax调用是异步的所以你的Ajax调用Ajax调用的仅仅是开始。它没有完成,直到成功功能

Your jquery to add the click handler is likely running before the content is actually in the page. Remember, the Ajax call is asynchronous so your ajax call is just the START of the ajax call. It does not complete until the success function.

我会建议把AJAX加载的内容的任何修改,在成功处理后,您实际上已经添加的内容到页面。

I would suggest putting any modifications of the ajax loaded content in the success handler after you've actually added the content to the page.

您也可以使用:

$(".editButton").live('click', function() {
    alert("Button has been clicked");
});

为现场处理程序将捕获所有点击在文档级别,然后检查,看看是否已经添加点击处理程序他们那里(所以它会工作,即使你指定它之前的元素添加到页面)但有些比后,他们已经添加到页面中您的成功处理程序上的对象直接操作效率较低。

as the live handler will catch all clicks at the document level and then check to see if you've added click handlers for them there (so it will work even if you specify it before the element is added to the page), but that is somewhat less efficient than operating directly on the objects AFTER they've been added to the page in your success handler.

这篇关于jQuery的不工作与动态创建的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆