使用Javascript启用引导按钮

时间:2018-01-13 11:30:53

标签: javascript html css twitter-bootstrap

同意,我的html页面上有一个引导按钮:

.....
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
...

    <div class="accept-btn">
      <button type="button" class="btn btn-warning disabled" onclick="acceptPmt()">Accept</button>
    </div>

我有JavaScript功能,应该激活(启用)它:

    function activateAcceptButton() {
        const accBtn = document.getElementsByClassName('accept-btn');
        //accBtn[0].disabled = false;
        //accBtn[0].classList.add('accept-btn-vis');
        //accBtn[0].setProperty("disabled", false);
        //accBtn[0].style.setProperty("enable", true);

        accBtn[0].removeClass('disabled');
    }

当调用该函数时,没有任何变化。你可以帮助我激活按钮吗?我如何更改js功能? 谢谢。

2 个答案:

答案 0 :(得分:1)

您使用的选择器不正确。 document.getElementsByClassName('accept-btn')会选择div。相反,您可以使用后代选择器(>)直接引用该按钮。您可以使用:document.querySelector('.accept-btn > button')

此外,您可以在按钮上使用.removeClass(),而不是.classList.remove()

&#13;
&#13;
function activateAcceptButton() {
  const accBtn = document.querySelector('.accept-btn > button');
  accBtn.classList.remove('disabled');
}

function acceptPmt() {}
&#13;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> ...

<div class="accept-btn">
  <button type="button" class="btn btn-warning disabled" onclick="acceptPmt()">Accept</button>
</div>


<button onclick="activateAcceptButton()">Activate</button>
&#13;
&#13;
&#13;

或者,您可以保持选择器不变,并选择div的第一个子项。该函数中的注释语句也需要相应地修改:

&#13;
&#13;
function activateAcceptButton() {
  const accBtn = document.getElementsByClassName('accept-btn');
  accBtn[0].children[0].classList.remove('disabled');
}
&#13;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> ...

<div class="accept-btn">
  <button type="button" class="btn btn-warning disabled" onclick="acceptPmt()">Accept</button>
</div>


<button onclick="activateAcceptButton()">Activate</button>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

在javascript中使用querySelector for bootstrap DOM

function activateAcceptButton() {
  /* selector class accept-btn of class btn,btn-warning,disable */
//  const accBtn = document.querySelector(".accept-btn [id=accept][type=button].btn.btn-warning.disabled");
  
  /* short */
  const accBtn = document.querySelector(".accept-btn [id=accept]");

  if (accBtn.classList) { 
    accBtn.classList.remove("disabled");
  } else {
    accBtn.className = accBtn.className.replace(/\bmydisabled\b/g, ""); // For IE9 and earlier
  }  
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="accept-btn">
  <button id="accept" type="button" class="btn btn-warning disabled" onclick="acceptPmt()">Accept</button>
</div>
    
<button onclick="activateAcceptButton()">Active</button>

CSS Selector for using querySelector