Question

Good day.

I get button from data .post

Code:

$(function () {

    $('.f1_start').on('click', function () {
        alert('hello');
    });

    $('.button_test').on('click', function () {
        $.post("update.php", {
                    ...
            },
            function (data) {
                    ...
                $('#div_test').html('').html(data); 
                //we get <button class="f1_start">test</button>
            });


    });

});

When I click on element page with class button_test from .post in div with Id div_test load button with class f1_start. But first script $('.f1_start').on('click',function(){ not work for this button.

Tell me please why script not working on load of .post ?

Was it helpful?

Solution

you are using on but not delegating it properly. you should always delegate it to the static parent container which is present in the document at the time of inserting dynamic element

try this

 $('#div_test').on('click','.f1_start',function(){
   alert('hello');
  });

link to read more about on delegated event

OTHER TIPS

As you declear the click for f1_start, is not there, you have to declear it on success:

<script>
$(function(){



$('.button_test').on('click',function(){
$.post("update.php", {
...
},
function(data){
...
$('#div_test').html('');.html(data); //we get <button class="f1_start">test</button>
$('.f1_start').on('click',function(){
alert('hello');
});
});


});

});
</script>

.on when used like that will only register once. You can register the event against an object you know will always be present.

You can give it some additional context such as a containing div so this may work better:

$('#div_test').on('click', '.f1_start', function(){
  //.....
});

You could also register the current .on event you have inside the callback which would have the same effect and be slightly more efficient but in general doing things like that are better done through a proper revealing module pattern to only register events you require.

Also as another note, there is no need to empty the html and then set it, setting it will replace it.

Try:

$('#div_test').on('click','.f1_start',function(){
    alert('hello');
});
$('#div_test').on('click','.f1_start', function(e){
  e.preventDefault();
  alert('hello');
});

<button> is equivalent to a submit so you must prevent the default action in jQuery or the page will redirect without ever showing you your alert.

Assuming .f1_start is inside #div_start

Try :

$("#div_test").on('click',".f1_start",function(e){
  alert("AWESOME");
})

At first, when the "scripts" loads the $('.f1_start')... the "selected element" not exists...

You need to unbind and set click again, once the post is loaded ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top