简体   繁体   中英

Onclick doesn't work in Firefox, but in Chrome - yes

Consider the following code...

function getItems(id, menu_id) {
    //some code
}  

$('#group-api').append('<li><a href="#" onclick="getItems(\''+data['group'][i]['id']+'\',\''+menu_id+'\');" role="tab" data-toggle="tab">'+data['group'][i]['menu_group']+'</a></li>');

This works if I use Chrome, but not for Firefox. Any solutions? Thanks.

Try the opposite way. Create the element via jQuery, append a .click() event on it, and then append it to the containter.

Code:

function getItems(id, menu_id) {
    // ...
}

$("<li><a href='#' role='tab' data-toggle='tab'>" + data['group'][i]['menu_group'] + "</a></li>")
    .appendTo("#group-api")
    .find("a")
    .click(function() {
        getItems(data['group'][i]['id'], menu_id);
    });

JSbin mock-up: http://jsbin.com/dosohatawe/1/edit?js,console,output


Reply to comment:

You always get the last value because you did not use a closure. Here is your (non-working) example updated with the use of closures:

for(var i = 0; i < data['group'].length; i++) {

    var id = data['group'][i]['id'];

    $("<li><a href='#' role='tab' data-toggle='tab'>" + data['group'][i]['menu_group'] + "</a></li>")
        .appendTo("#group-api")
        .find("a")
        .click(
            (function(a, b) {
                return function() {
                    getItems(a, b);
                };
            })(id, menu_id)
        );

}

I haven't tested it, but I think it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM