Ajax包括一个页面

时间:2012-08-15 19:52:29

标签: jquery ajax

我可以在Ajax的加载页面上创建一些函数吗? 即。

$(function() {
    $.ajax({
        url: "loaded.php",
        success: function(data) {
            $("#content").html(data);
        }
    });
    $("a#edit").click(function(e) {
        e.preventDefault();
        var newVal = $(this).closest("tr").find("#collapse").html();
        $(this).html(newVal);
    });
});

a#edit#collapse都是loaded.php的元素,此代码位于index.php页面中......此代码是否有效?

2 个答案:

答案 0 :(得分:2)

将html添加到#content或使用委派后,您有两个选项可以在成功函数中附加处理程序。

选项1

    success: function(data) {
        $("#content").html(data);
        $("#edit").click(function(e) {
            e.preventDefault();
           var newVal = $(this).closest("tr").find("#collapse").html();
           $(this).html(newVal);
        });
    }

选项2

$(function() {
    $.ajax({
        url: "loaded.php",
        success: function(data) {
            $("#content").html(data);
        }
    });
    $("#content").on('click', '#edit', function(e) {
        e.preventDefault();
        var newVal = $(this).closest("tr").find("#collapse").html();
        $(this).html(newVal);
    });
});

http://api.jquery.com/on/

答案 1 :(得分:0)

如果您的$(“#edit”)元素是您的ajax返回的内容,则此代码不起作用。您需要将该代码块移动到成功回调中。

$(function() {
    $.ajax({
        url: "loaded.php",
        success: function(data) {
            $("#content").html(data);
            $("a#edit").click(function(e) {
                e.preventDefault();
                var newVal = $(this).closest("tr").find("#collapse").html();
                $(this).html(newVal);
            });
        }
    });
});
相关问题