to sum it up quickly.. I have a jQuery tooltip on one of my table elements with a specific data attribute to select it. it works great, makes an ajax request, returns data and puts it in the tooltip. only problem is every time i mouse over the table element the ajax request gets triggered again.

    $('p').tooltip({ 
        items: "[data-whatever]",
        content: function(){
            var el = $(this),
                content = el.data('ajax-content');
            if(content)
                return content;    
            return 'waiting for ajax';
        },
        open: function(){
            var elem = $(this),
                id = elem.data('whatever');
            $.ajax('/echo/html/' + id).always(function(res)  {
                elem.tooltip('option', 'content', res[0].label);
                elem.data('ajax-content', res[0].label);
            });
        }
    });

all of this works fine ( i made a few changes to the code so its not identical to what i did because its incorporated into my works module pattern).. but is there a simple way to only hit the open function one time?

any help would be appreciated!

有帮助吗?

解决方案

You can check if 'ajax-context' data is already set. If so do not trigger the ajax request.

$('p').tooltip({ 
    items: "[data-whatever]",
    content: function(){
        var el = $(this),
            content = el.data('ajax-content');
        if(content)
            return content;    
        return 'waiting for ajax';
    },
    open: function(){
        var elem = $(this),
            label = elem.data('ajax-content');
        if (label) {
          elem.tooltip('option', 'content', label);
        } else {
          var id = elem.data('whatever');
            $.ajax('/echo/html/' + id).always(function(res)  {
                elem.tooltip('option', 'content', res[0].label);
                elem.data('ajax-content', res[0].label);
            });
        }
    }
});

其他提示

Try this, store ajax response in element data, now check in open event if tooltip exists in data, if yes show it else cal ajax.

$('p').tooltip({ 
    items: "[data-whatever]",
    content: function(){
        var el = $(this),
            content = el.data('ajax-content');
        if(content)
            return content;    
        return 'waiting for ajax';
    },
    open: function(){
        if($(this).data("ajax-content") == undefined) {
            var elem = $(this),
                id = elem.data('whatever');
            $.ajax('/echo/html/' + id).always(function(res)  {
                elem.tooltip('option', 'content', res[0].label);
                elem.data('ajax-content', res[0].label);
            });
        }
        else {
            $(this).tooltip('option', $(this).data("ajax-content"));
        }
    }
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top