Search code examples
jqueryhtmljquery-pluginsjquery-attributes

jQuery's attr(...) in function parameter is undefined


I'm using a jQuery plugin called webuiPopover. It adds a popover to links. When the user hovers a link, the content of the popover is fetched through AJAX. This requires a certain url with appropriate parameters.

So this is the code :

$(document).ready(function() { 
    $(".qa-user-link").webuiPopover({
        placement:"auto",
        trigger:"hover",
        type:"async", 
        cache:false,
        url:"./qa-plugin/q2a-user-popover/qa-user-popover-details.php?handle="+$(this).attr("data-id")+"&incdir=%2Fhome%2Fpeatar5%2Fpublic_html%2Fbiophilie%2Fqa-include%2F",
        content:function(data) {return data;}
    });
});

As you can see I calculate the 'url' making use of jQuery's attr(...) function. Unfortunately that little piece of code always returns 'undefined'.

If I use the same piece of code ($(this).attr("data-id")) in the content parameter (to give function (data) {return $(this).attr("data-id");} it works fine.

What's going wrong?


Solution

  • this refers to the document inside the callback of $(document).ready. It works inside the content callback, because the plugin is binding the element to content when it calls it.

    If you want to have a distinct url for each popover, you'll have to bind the popover plugin separately for each element:

    $(document).ready(function() { 
        $(".qa-user-link").each( function ( ) {
            var $this = $(this);
            $this.webuiPopover({
                placement:"auto",
                trigger:"hover",
                type:"async", 
                cache:false,
                url:"./qa-plugin/q2a-user-popover/qa-user-popover-details.php?handle="+$this.attr("data-id")+"&incdir=%2Fhome%2Fpeatar5%2Fpublic_html%2Fbiophilie%2Fqa-include%2F",
                content:function(data) {return data;}
            });
        });
    });