Jquery:按钮创建,事件处理程序,问题

时间:2015-02-01 21:52:38

标签: jquery button javascript-events

好吧,自从我使用javascript或Jquery已经有一段时间了,所以我确定我在这里犯了一个愚蠢的错误,但我无法弄清楚我做错了什么。我的一个JS函数似乎在页面加载时运行,但在我想要的时候却没有(当点击一个按钮时)。

我正在尝试从数据库中提取信息。我正在尝试测试用PHP编写的API,因此我创建了一个“测试”页面。页面上还有其他数据字段,但它们都可以正常工作。我为页面创建了一个JS文件,现在有3个函数:

“document.ready”功能,

$(document).ready( function(){
    $( "#show_users" ).click(ShowUsers);
    $(".log_btn" ).click( ShowBSLogs(this.id));
});

使用事件处理程序,第一个用于html中的单个按钮,第二个用于动态创建的一组按钮。

这些事件中的每一个都应触发另外两个功能之一:

function ShowUsers() {
    $.post( "show", function(data,status){
        console.log(data[0]);
        $( "#output" ).empty().append( "<table id='user_table' width='100' border-color='black'><tr><th>First Name</th><th>Last Name</th><th>Email</th><th>Logs</th></tr></table>" );
        data.forEach(function(user) {
            $( "#user_table" ).append( "<tr><td>" + user.first_name + "</td><td> " + user.last_name + "</td><td> " + user.email + "</td><td><button class='log_btn' id=' "+user.u_id+" '>Logs</button></td></tr>");
        });

    });
}

function ShowBSLogs(u_id) {
    $.post( "show/uid", {id: u_id}, function(data,status){
        console.log(data);
        console.log("fired");
    });
}

当页面加载时,会调用ShowBSLogs,并且由于它没有传递变量,因此会导致错误。当我单击原始按钮并调用ShowUsers时,它运行正常,我得到一个包含姓名,电子邮件和一个id与用户关联的按钮的表,但是当我单击该按钮时,ShowBSLogs isn没打电话。

我很乐意从其他文件中发布更多代码,但我相当肯定错误就在这里。如果您还有其他需要,请告诉我。

任何?提前谢谢。

1 个答案:

答案 0 :(得分:0)

通过创建一个按钮对象然后将其附加到表行来管理解决此问题,然后设置事件处理程序(.click)。我不确定为什么这样做有效,因为我在这个最终的解决方案上尝试了很多不同的变化而且都没有用,但是我发布了我的解决方案,以防它帮助别人。

test.js:

$(document).ready( function(){
    $( "#show_users" ).click( function() { ShowUsers();         });
    $( ".log_btn"    ).click( function() { ShowBSLogs(this.id); });
});


function ShowUsers() {
    $.post( "show", function(data,status){
        console.log(data[0]);
        $( "#output" ).empty().append( "<table id='user_table' width='100' border-color='black'><tr><th>First Name</th><th>Last Name</th><th>Email</th><th>Logs</th></tr></table>" );
        data.forEach(function(user) {
            var row = $(" <tr><td>" + user.first_name + "</td><td> " + user.last_name + "</td><td> " + user.email + "</td></tr>");
            var button = $('<button/>', {
                text: 'Logs',
                class: 'log_btn',
                id: user.u_id });
            row.append(button);
            $( "#user_table" ).append(row );
        });
        $( ".log_btn" ).click( function() { ShowBSLogs(this.id); }); //set event handler

    });
}


function ShowBSLogs(u_id) {
    console.log(u_id);
    $.post( "show/uid", {id: u_id}, function(data,status){
        console.log(data);
        console.log("fired");
    });
}
相关问题