How to make Intro.js select the element that dynamically generated after page load

时间:2016-04-15 15:12:14

标签: javascript jquery

JsFiddle: JsFiddle

I have a bootstrap popover window and a button to call the popover out.

My goal is: I want to have Intro.js feature to introduce:

step 1: click the button;

step 2:Here is the popover window.

Intro.js provides an option that can pre-define the steps programmically. So here's my code of introjs:

var intro2 = introJs();
  intro2.setOptions({
      exitOnOverlayClick: true,
      showBullets: false,
      //showStepNumbers: false,
      steps: [
      {
        element: document.querySelector('#saveSelection'),
        intro: "Click this button to call popover window.",
        position: 'top'
      },
      {
        element: document.querySelector('.popover.fade.top.in'),
        intro: "popover windown",
        position: 'top'
      }, 
      ],
  }).setOption('doneLabel', 'Close').start();
  });

But my problem is that while I was in the introJs layout(step1), it located the button but this time popover window wasn't called out. Then I went ahead to click the button, popover called out, then I click next on Introjs, it couldn't locate my popover window.

The reason probably is because when introJs was initialized at the first time. it has already scanned those elements in the steps I defined in intro2.setOptions, but since the popover is a dynamic element so introJs couldn't find a popover named class="popover fade top in" at the initial stage.

Same issue happened for bootstrap Modal.

Any solutions?

2 个答案:

答案 0 :(得分:1)

如果我没弄错的话,你遇到与问Event binding on dynamically created elements?

相同的问题

在这种情况下,你必须将一个函数绑定到dinamic created元素。

答案 1 :(得分:0)

如果还有人在 google 上寻找解决方案,我想出了一个可行的解决方案,它可以应用于将步骤的元素附加到动态对象的其他情况。

在介绍对象 init 上,添加以下内容以在加载步骤之前启用特定于步骤的函数调用。 (function creds)

intro2.onbeforechange(function(){
  if (this._introItems[this._currentStep].preChange) {
    this._introItems[this._currentStep].preChange();
  }
});

在 popover 步骤中,使用 preChange 属性调用函数并动态设置该步骤的元素和位置。

  {
    intro: "popover windown",
    preChange: function(){
      this.element = document.querySelector('.popover.fade.top.in');
      this.position = "top";
    }
  },

请注意,如果在移动到 popover 步骤时弹出框未处于活动状态,则代码通常会中断,因此您需要在进入该步骤之前强制/检查弹出框是否打开。否则,假设本示例中的弹出框可见,则按预期运行

JSFiddle