1

Script below create button and event dynamically. I want to bind data to click event. But bind() function failed, click event just won't trigger. Anyway, click event successfully triggered if I'm using on() function.

http://jsfiddle.net/hzLv1r6s/2/

    function showMessage(evt) {
        alert(evt.data.message);
    }

$(document).ready(function () {
    var activeDiv;
    var pVar = { message:'Hello from a paragraph'};
    $("a").on("click", function () {

        if (activeDiv === $(this).attr('id')) {
            $('#__div').hide('slow');
            activeDiv = '';
            return;
        }
        $('.box1').empty();
        var guts = 
            '<div id="__div" style="display:none;">' +
            '<input type="text" id="__text" value="' + $(this).attr('data-content') + '"/><br>' +
            '<button id="__internal" value="aaa">Submit</button>' +
        '</div>';

        //this one doesn't work on click event
        $('#__internal').bind('click',pVar,showMessage);

        $($.trim(guts)).appendTo('.box1');
        $('#__div').show('slow');
        activeDiv = ($(this).attr('id'));
    });

    /*
    //this one does work on click event
    $('.box1').on('click','#__internal',function(event){
       //alert(event.target.value);
        alert($('#__text').val());
    });
    */

});

1 Answer 1

1

You need to use event delegation at this context,

 $('.box1').on('click','#__internal' , showMessage);

Or try to bind the event to it after that html string got appended into the DOM.

 $($.trim(guts)).appendTo('.box1');
 $('#__internal').bind('click',pVar,showMessage);

NOTE: But i don't know why are you refusing to use event delegation here.

DEMO created without event delegation.

Sign up to request clarification or add additional context in comments.

1 Comment

many thanks for the answer and event delegation tips. Actually I'm done the script by grasping others code and modify as I need, thats why I'm lack of the concept.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.