Javascript将不存在的类分配给变量

时间:2019-12-16 17:52:02

标签: javascript

点击此按钮后:

var option_btn = document.querySelectorAll('[class*="sp_choice_type"]')[1]

以下按钮将在网络上可用:

var refuse = document.querySelector('[class*="priv-reject-btn"]')[0]

,但是在单击之前无法使用,下面的代码将不起作用:

var option_btn = document.querySelectorAll('[class*="sp_choice_type"]')[1]
option_btn.addEventListener('click', ()=>{
    setTimeout(()=>{
        var refuse = document.querySelector('[class*="priv-reject-btn"]')[0];
        refuse.addEventListener('click',() =>{
            console.log("Eureka")
    })
    }, 5000)
})

我也尝试过一些Promises,但也没有用。

该案例位于zonebourse.com网站上,该按钮带有波顿免责声明中的“选项”按钮和单击“选项”后立即触发的“拒绝拒绝”

1 个答案:

答案 0 :(得分:0)

在没有看到您所遇到问题的可行示例的情况下,很难确定问题是什么。似乎您试图在用户单击另一个按钮(按钮A)时向页面添加一个新按钮(按钮B),并在按下按钮B时采取措施。考虑到这一点,下面是一个向页面添加按钮并在单击该新按钮时执行操作的示例。该代码已注释,但是如果您有任何疑问或不清楚的地方请告诉我,我会改善答案。

// find all option buttons
var options = document.querySelectorAll('.option');
// loop over all option buttons
[...options].forEach((opt) => {
  //  wire event handler for click
  opt.addEventListener('click', (e) => {
    // check if we have already added the button
    if (!e.target.actionButton) {
      // return a promise instead of setTimeout for better async
      return new Promise((resolve, reject) => {
        // create the new button
        var btn = document.createElement("button");
        // pull out the option attribute to make it easier to reference later
        var optionAttr = e.target.getAttribute('data-option')
        // store the option for this button
        btn.setAttribute('data-option', optionAttr);
        // wire the click handler for this button
        btn.addEventListener('click', (ev) => {
          // get the option
          var option = ev.target.getAttribute('data-option');
          // just log for now
          console.log(`you clicked ${option}`)
        });
        // set the text of the button
        btn.innerHTML = `Action Button ${optionAttr}`;
        // store a reference to the action button on the option button
        e.target.actionButton = btn;
        // append the new action button to the action button container
        document.querySelector('#buttons').append(btn);
        // resolve the promise
        resolve();
      });
    }
  })
});
button {
  display: inline-block;
  margin: .5em;
  padding: .5em;
}

#buttons button {
  display: inline;
  margin: .5em;
  padding: .5em;
}
<button class="option" data-option="1">
Option 1
</button>
<button class="option" data-option="2">
Option 2
</button>
<div id="buttons">

</div>