【问题标题】:.click function with an Ajax post.click 函数与 Ajax 帖子
【发布时间】:2013-06-24 22:10:33
【问题描述】:

所以我得到了一个选择菜单,当用户选择一个选项时,它通过 ajax 调用一个 post 函数,该函数通过 PHP 生成一些表行,然后返回它的 html 编码。在其中,有一个添加按钮。

我想要做的是,当用户单击添加按钮时,会显示一个表单。 但是由于某种原因,它不起作用...

代码如下:

$(document).ready(function () {
    $(".add_form").hide();

    $("#console").change(function () {
        var id = $(this).val();
        var dataString = 'console_id=' + id;

        $.ajax({
            type: "POST",
            url: "generate-games-list",
            data: dataString,
            cache: false,
            success: function (html) {
                $("#games_table_body").html(html);
            }
        });

    });

    $(".add_button").click(function () {
        alert("HELLO");
        var id = this.id;

        $.post('manage_games', 'game_id=' + id, function (response) {
            alert(response);
        });

        $("#game_id").val(id);
        $(".add_form").show();

    });

});

这是返回表格行的 PHP 代码:

$console = Console::find(Input::get('console_id'));
    $type = GameType::find(Input::get('type_id'));

    if(!Input::has('console_id'))
        return "Error";
    else{

        foreach($console->games()->get() as $console_game){
            $available_consoles_string = "";
            $game_types_string = "";

            //Get all the consoles the game can be played on
            foreach($console_game->consoles()->orderBy('name', 'asc')->get() as $available_consoles){
                $available_consoles_string = $available_consoles_string . " " .$available_consoles->name .", ";
            }

            //Get all the types that the game falls in
            foreach($console_game->types()->orderBy('type', 'asc')->get() as $game_types){
                $game_types_string = $game_types_string . " " .$game_types->type .", ";
            }   

            return "<tr><td>" .$console_game->name. "</td><td>". $available_consoles_string. "</td><td>" .$game_types_string. "</td><td><input type='button' id='" .$console_game->id. "' class='add_button' value='Add'/> / View</td></tr>";

        }
    }

知道为什么它不起作用吗?当我的意思是不工作时,我的意思是警报没有显示,但我在 Chrome 控制台上没有收到任何错误...

谢谢, 阿拉

【问题讨论】:

  • 在父容器上使用 on() 方法。例如。 $('#games_table_body').on('click', '.add_button', function() { ... });.
  • 您应该在console.change ajax 请求的成功函数中设置点击处理程序。准备就绪时,按钮还没有出现,所以处理程序什么都没有...

标签: php jquery ajax button


【解决方案1】:

只需使用.on():

$(document).on("click", ".add_button", function(){
    // your event code
});

当您的 js 运行时,click 事件将附加到具有 .add_button 类的所有当前元素。但是,您通过 ajax 添加了额外的按钮,这些按钮不会触发相同的 click 事件。

要解决此问题,请使用上面的代码。它将事件附加到document,因此即使您在页面加载后添加按钮,click 事件也会被它们触发。

【讨论】:

    猜你喜欢
    • 2018-03-06
    • 2021-12-09
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    相关资源
    最近更新 更多