【问题标题】:Set attributes to the button but only works when I click it twice为按钮设置属性,但仅在我单击两次时才有效
【发布时间】:2021-12-28 01:56:35
【问题描述】:

我使用一些引导元素为我的按钮设置了一些属性,但是当我第一次单击该按钮时它不起作用。我需要单击按钮外的某处,然后再次单击该按钮。

我已经通过在 onload 中调用函数并在按钮中再次调用它来解决这个问题,但是现在我无法再这样做了,所以我想知道是否有其他方法可以解决这个问题?

这是我的代码: https://jsfiddle.net/a22177861/x381z0h6/6/

HTML:

 <button type="button" class="btn btn-warning" onclick="PopOver(this,'Hi','Thank','You');">ClickMe!</button>

JS:

function PopOver(myObj, mgr, Adate, Vdate) {
        $(function () {
            myObj.setAttribute("data-container", "body");
            myObj.setAttribute("data-toggle", "popover");
            myObj.setAttribute("data-placement", "bottom");
            myObj.setAttribute("data-html", "true");
            myObj.setAttribute("data-trigger", "focus");
            myObj.setAttribute("title", "otherInfo");
            myObj.setAttribute('data-content', "MGR:"+mgr+"<br />DATE1:"+Adate+"<br />DATE2:"+Vdate);

            $("[data-toggle='popover']").popover();
        });
    } 

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript bootstrap-4


    【解决方案1】:

    您代码中的这个$('[data-toggle="popover"]').popover() 会初始化弹出框,因此您必须单击两次才能触发它。

    根据Bootstrap的popover documentation

    显示元素的弹出框。在 popover 实际显示之前(即在 shown.bs.popover 事件发生之前)返回给调用者。这被认为是弹出框的“手动”触发。标题和内容均为零长度的弹出框永远不会显示。

    您可以使用.popover('show') 手动触发弹出框。

    会是这样的:

    function PopOver(myObj, mgr, Adate, Vdate) {
      myObj.setAttribute("data-container", "body");
      myObj.setAttribute("data-toggle", "popover");
      myObj.setAttribute("data-placement", "bottom");
      myObj.setAttribute("data-html", "true");
      myObj.setAttribute("data-trigger", "focus");
      myObj.setAttribute("title", "otherInfo");
      myObj.setAttribute('data-content', "MGR:"+mgr+"<br />DATE1:"+Adate+"<br />DATE2:"+Vdate);
    
      $("[data-toggle='popover']").popover('show');
    } 
    

    【讨论】:

    • 我的问题完美解决了,非常感谢!!
    【解决方案2】:

    我建议您以更友好的方式编写代码。一些死字段可以直接用 HTML 编写

        <button type="button" class="btn btn-warning" data-container="body" data-toggle="popover" data-trigger="focus" data-placement="bottom" data-html="true" title='otherInfo' onclick="PopOver(this,'Hi','Thank','You');">ClickMe!</button>
    
    function PopOver(myObj, mgr, Adate, Vdate) {
      myObj.setAttribute('data-content', "MGR:"+mgr+"<br />DATE1:"+Adate+"<br />DATE2:"+Vdate);
      $("[data-toggle='popover']").popover('show');
    } 
    

    【讨论】:

    • 感谢您的建议!我会记住的
    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    • 2019-10-28
    • 2014-05-10
    • 1970-01-01
    相关资源
    最近更新 更多