【问题标题】:Bootstrap 4 not updating onclick attribute of popoverBootstrap 4 未更新弹出框的 onclick 属性
【发布时间】:2019-12-12 07:51:21
【问题描述】:

我试图在 bootstrap 4 中创建一个带有嵌套按钮的弹出框,但是在使用 button 元素更新该弹出框的 data-content 属性时,它会更新该元素,但缺少唯一的 onclick 属性。

我尝试使用按钮而不是锚标记,也尝试使用纯 JavaScript 更新元素,但问题仍然存在。 我已经有 popover 属性 html: true

这是更新的js代码

function popoverUpdate(cart){
    console.log("pop update");
    var popoverdata = "<ol>"
    for (i in cart){
        popoverdata +="<li>Item :" + i + ", Quantity : " + cart[i] + "</li>";
    }
    popoverdata += "</ol><a href='#' onclick='console.log(5);' class='btn btn-secondary'>Hello</a>";
    $('#cartVal').attr('data-content', popoverdata);
    $('#cartVal').popover('show');
}

我正在更新其数据内容的 HTML 元素


<button class="btn btn-primary m-lg-2" title="In Cart" id="cartVal" data-content="this is default content" data-toggle="popover" data-placement="bottom"
      data-trigger="focus">Cart(0)</button>

updation element(expected) => 

<a href='#' onclick='console.log(5);' class='btn btn-secondary'>Hello</a></pre>

instead updates to

<a href="#" class="btn btn-secondary">Hello</a>

as you can see onclick attribute is missing

【问题讨论】:

    标签: javascript jquery bootstrap-4 popover


    【解决方案1】:

    这是一个技巧。首先,启用 data-html 属性,然后为单击按钮设置事件侦听器,最后阻止默认行为

    function popoverUpdate(cart){
        console.log("pop update");
        var popoverdata = "<ol>"
        for (i in cart){
            popoverdata +="<li>Item :" + i + ", Quantity : " + cart[i] + "</li>";
        }
        popoverdata += "</ol><a href='#' class='btn btn-secondary popoverButton'>Hello</a>";
        $('#cartVal').attr('data-html', true);
        $('#cartVal').attr('data-content', popoverdata);
        $('#cartVal').popover('show');
        document.querySelectorAll('.popover-body a.popoverButton').forEach((button, index) => button.addEventListener('click', (event)=>{
        event.preventDefault();
        console.log(5);
        //put the rest of your code here
        }));
    
    }
    

    【讨论】:

    • 首先感谢您的回复,我得到了您的方法,是的,效果很好。但是,我仍然想知道这种弹出框行为的原因,因为如果将来我需要添加更多具有复杂功能的按钮,它会变得更加复杂。
    • 说得好,当您添加更多按钮时,这不是一个非常实用的解决方案。为什么弹出框会这样,我也不知道,但如果你弄清楚了,请分享。
    • 更新:我找到了这个答案。它可能会解决您的问题stackoverflow.com/a/57418074/11854340
    • 成功了!!非常感谢,因为我使用了一种非常规的方式来呈现该按钮,这正是我正在寻找的答案............干杯!
    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2019-11-18
    • 2018-09-23
    • 1970-01-01
    • 2019-11-06
    • 2018-05-22
    • 1970-01-01
    相关资源
    最近更新 更多