如何使用 jQuery 更改 Bootstrap 按钮属性

How to Change Bootstrap Button Properties and Attributes using jQuery

我是 Bootstrap 和 jQuery 的新手,我无法确定更改 js 文件中 html 元素的特性和特性的最佳实践。

例如,我有一个默认启用并包含一些文本的按钮。在单击事件中,我想禁用按钮,但同时更改按钮文本和颜色。

我在下面提供了一些示例代码,您可以在其中看到我一直在进行一些按钮更改并测试结果。另外,我已经提到在使用 jQuery v 1.6 或更高版本时我应该使用 .prop 而不是 .attr,我正在为我的项目使用 jQuery v 3.2.1 .

HTML

<!-- Submit Button -->
<div class="form-group">
    <a href="#" class="btn btn-primary" data-toggle="modal" data-target="#submitModal" id="submitButton">Submit</a>
</div>

JavaScript

$(document).ready(function() {
$("#submitButton").click(function(){

  //Disable button
  // $("#submitButton").prop('disabled', true) //Did not work
  // $("#submitButton").attr('disabled', true) //Did not work
  $("#submitButton").addClass('disabled')

  //Use aria-disabled when button disabled for screen readers
  $("#submitButton").prop('aria-disabled', true) //How to confirm this worked?
  //$("#submitButton").attr("aria-disabled","true") //use `.attr` instead of `.prop`?

  //Change button color
  $("#submitButton").button('reset').addClass('btn-success'). //Do I need `.button('reset')? Works fine without this code snippet as shown below in next line of code

  //Change button text
  $("#submitButton").html('Submission received') //Again, should I use `.button('reset') before `.html('Submission received')?

  })
})

关于disabled,也就是一个属性,所以用.prop().

关于background-color和text color,就是要用.css()来改变。

关于按钮文字,即.text()

$("#submitButton").click(function(){
  console.log("HEY");
  $(this).prop("disabled",true);
  $(this).css({"background-color":"red", "color":"white"});
  $(this).text("I'm disabled");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="submitButton">Submit</button>

这与Bootstrap无关...

"chained"方式:

$("#submitButton").click(function(){
  console.log("HEY");
  $(this).prop("disabled",true)
    .css({"background-color":"red", "color":"white"})
    .text("I'm disabled");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="submitButton">Submit</button>