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

问题描述 投票:0回答:1

单击此按钮后:

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网站上,带有来自博顿免责声明的“选项”按钮和单击“选项”后立即触发的“拒绝拒绝”

javascript
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.