简体   繁体   中英

Button does not call function when clicked

I'd like a function t run when a button is clicked. It works fine when I approach it like so in the html body

<div type="button" id="decline" class="btn btn-danger mrs"></div> 

However, I need it to work within the below code block, which is within a underscore.js wrapper. At the moment the function won't execute using the below, I'd like to understand why? is the id in the wrong place?

$('#containerFriendsPending').empty();
_.each(friends, function(item) {
    var wrapper = $('<div class="portfolio-item-thumb one-third"></div>');
    wrapper.append('<div type="button" 
                         id="decline" 
                         class="btn btn-danger mrs">' + 
                   'Decline' + 
                   '</div>');
    $('#containerFriendsPending').append(wrapper);
});

Solved this myself.

The following needed to be added within the original question main code block

$('.decline').click(function() {
Friendrequest_decline();
});

So doing this works.

$('#containerFriendsPending').empty();
    _.each(friends, function(item) {
    var wrapper = $('<div class="portfolio-item-thumb one-third"></div>');
    wrapper.append('<div type="button" id="decline" class="btn btn-danger mrs">' + 'Decline' + '</div>');
    $('#containerFriendsPending').append(wrapper);

$('.decline').click(function() {
Friendrequest_decline();
});

                                });

As you didn't provide the code that launches the click event it's hard to debug, but I'm going to assume it's actually the most common mistake that causes this problem: You are binding the click event before the element actually exists. That way, the browser will not know the new element also needs the click event.

Example:

$('.test').click(someFunction);
$('body').append( $('<div class="test">Click me!</div>');

This will not work, because the click event is bound first and the element is created later.

The jQuery .on() function can handle that by also watching for new elements that are created in the DOM:

$('body').on('click', '.test', someFunction);
$('body').append( $('<div class="test">Click me!</div>');

Now it will run someFunction successfully.

While the code solution you posted will work the first time:

$('#decline').click(function() {
    Friendrequest_decline();
});

It will not work after the wrapper code is replaced, as per your answer. You must use .on() to delegate the event:

$(document).on('click', '#decline', function() {
    Friendrequest_decline();
});

or

$('#containerFriendsPending').on('click', '#decline', function() {
    Friendrequest_decline();
});

Eg:

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

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