简体   繁体   中英

Bootstrap popover: change the content of a popover on a dynamic created element

I have this popover script I use on static element that is working great:

$(".popover-class").popover({
        title: fetchTitle,
        content: 'loading...', 
        html: true,
        placement: 'right'
    }).on('shown.bs.popover', function () {
        var popover = $(this).attr('data-content', fetchData).data('bs.popover');
        popover.setContent();
        popover.$tip.addClass(popover.options.placement);
});

Where "fetchData" is a function that call an ajax request on a script that retrieve some data from the myssql.

In another page I want to do the same thing, but on dynamically generated elements. I understode I have to call the popover from the "body", but then the ".attr('data-content'" is no more working and I don't understand why.

Here is the non-working script:

$("body").popover({
        title: fetchTitle,
        content: 'loading...',
        container: 'body',
        html: true,
        placement: 'right',
        trigger: "hover",
        selector: '.popover_ajax'
    }).on('shown.bs.popover', function () {
        console.log('test'); // <- this is working 
        var popover = $(this).attr('data-content', 'new text').data('bs.popover');
        popover.setContent();
        popover.update();
        // <-- all this is not working, the popover remain with text "loading.."

    });

The popover is generating but it stays with text "loading..", it won't change. Am I missing something? With 'body' maybe somethings should be called differently?

You are trying to get the attribute from the body element by using this .

$("body").popover({
    title: fetchTitle,
    content: 'loading...',
    container: 'body',
    html: true,
    placement: 'right',
    trigger: "hover",
    selector: '.popover_ajax'
}).on('shown.bs.popover', function () {
    var popover = $(event.target).attr('data-content', 'new text').data('bs.popover');
    popover.setContent();
    popover.update();

});

$('.popover_ajax') will match all elements on the page, you want to just match the one that was clicked. The event handler will receive the event as a parameter, and you can find the event target from that:

.on('shown.bs.popover', function (event) { 
    var popover = $(event.target).attr('data-content', 'new text')... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM