Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Jquery, bind a dynamic selector with 'On' method (not a string)

I want to use the 'On' function to attach a event because the others are deprecied(live, delegate,click...).

But the problem is : if we generate objects, we need to use a selector in parameters and this parameter is a string!!

Sample : (context : dynamic table)

//Wrong way

$("#dataTable tbody tr").on("click", function(event){
    alert($(this).text());
});

//Good way

$("#dataTable tbody").on("click", "tr", function(event){
    alert($(this).text());
});

Now How I do if I want use 'find' method in order to avoid that

    // ?? (find div)
    $("#dataTable tbody").on("click", "tr > ul > li > ul > li > div", function(event){
            alert($(this).text());
        });

   // What I would like to do
    $("#dataTable tbody").on("click", $(this).find("div"), function(event){
            alert($(this).text());
        });

   //and I don't want to do this :
    $("#dataTable tbody").find('div').on("click", function(event){
            alert($(this).text());
        });

Thank you !

like image 539
Frédéric GRATI Avatar asked Feb 06 '26 13:02

Frédéric GRATI


1 Answers

The working equivalent to:

// What I would like to do
$("#dataTable tbody").on("click", $(this).find("div"), function(event){
    alert($(this).text());
});

is...

// What I would like to do
$("#dataTable tbody").on("click", 'div', function(event){
    alert($(this).text());
});

If you to target div's inside the nested list, then you might be able to get away with:

// What I would like to do
$("#dataTable tbody").on("click", 'ul ul div', function(event){
    alert($(this).text());
});

... but it depends if you have other ul's in your tbody; you only need to be specific enough in your selector to remove the other elements from consideration. Very rarely would you need to be as specific as tr > ul > li > ul > li > div, and in that case it'd be best to apply a class to an element nearer the div (or the div itself) and select around that instead.

Also note that it is only live() that is depreciated. At the time of writing (1.7.2) delegate() is not, although I believe it will be in 1.8.

There is no talk of depreciating click() or it's shortcut counterparts.

like image 77
Matt Avatar answered Feb 09 '26 07:02

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!