开发者

jQuery - calling function with parameters inside method

开发者 https://www.devze.com 2023-01-30 22:16 出处:网络
I\'m wondering how 开发者_JS百科is possible to call a function with parameters inside a method. I have 2 functions and i\'d like to call function deleteCode() when clicked on list element which is cre

I'm wondering how 开发者_JS百科is possible to call a function with parameters inside a method. I have 2 functions and i'd like to call function deleteCode() when clicked on list element which is created by addCode() function. I'm sure the solution is really simple, but i just can't see it right now. Many thanks!

function addCode(code) {
    $('#codeList').append('<li class="codeList" onClick="deleteCode(code);">' + code + '</li>');
}

function deleteCode(code) {
    $('#'+code).remove();
}


Do it unobtrusive and you're fine.

function addCode(code) { 
    $('#codeList').append($('<li>', {
        'class':    'codeList',
        'text':     code,
        'click':    function(e) {
             deleteCode(code);
        }
    }));
}

Ref.: $()


Create the <li> element via code rather than appending raw HTML.

function addCode(code) {
    // Create the <li>
    var newEl = document.createElement("li");
    newEl.className = "codeList";

    // Assign the click function via jquery's event helper.
    $(newEl).click(function(code) {
        // Call your deleteCode function and pass in the given parameter.
        deleteCode(code);
    });

    // Append the new element to the codeList node.
    $(#codeList).append(newEl);
}


You can try:

function addCode(code) {
$('#codeList').append('<li class="codeList" onClick="deleteCode(' + code + ');">'+code+'</li>'); 
}


You can do that like this:

function addCode(code) {
    $('<li class="codeList">' + code + '</li>').click(function() {
        deleteCode(code);
    }).appendTo('#codeList');
}

function deleteCode(code) {
    $('#'+code).remove();
}

...or more simply:

function addCode(code) {
    $('<li class="codeList">' + code + '</li>').click(function() {
        $('#'+code).remove();
    }).appendTo('#codeList');
}

When using a library like jQuery (or even when not, frankly), there's virtually never any reason to use the old-style onclick attributes for setting up handlers. In the above, I've replaced it with the click function, which sets up a handler when the user clicks the element.

Note: Lazarus notes that your code is removing an element by id using the code value:

$('#' + code).remove();

...but that the code doesn't produce an element with that ID. I assume you've added that element with some other code elsewhere, and that the goal isn't to remove the li you've added with this code.

If you did want to remove that same li on click, no need for an ID at all:

function addCode(code) {
    $('<li class="codeList">' + code + '</li>').click(function() {
        $(this).remove(); // <== Changed here
    }).appendTo('#codeList');
}
0

精彩评论

暂无评论...
验证码 换一张
取 消