可以在jquery时单击一个按钮

时间:2015-04-08 13:15:03

标签: jquery

让我说我有两个按钮,当我点击button1时,我想要禁用button2,同样点击按钮2被禁用按钮1。我想要一个按钮可以点击。我怎么能这样做?提前谢谢。

<div class="container">

<button type="button" id="button1" class="buttons">button1</button>
<button type="button" id="button2" class="buttons">button2</button>

</div>


$( document ).ready(function() {
  $( "buttons" ).click(function() {

  });
});

我在考虑使用.attr('disabled', true)

2 个答案:

答案 0 :(得分:4)

试试这个:在jQuery中使用类选择器时,需要在classname之前放置.(点)。您可以使用siblings()将所有按钮置于同一级别,并使用prop('disabled',true)来禁用按钮。

$( document ).ready(function() {
  $( ".buttons" ).click(function() {
     $(this).siblings('.buttons').prop('disabled',true);
  });
});

<强> JSFiddle Demo

答案 1 :(得分:3)

<div class="container">

<button type="button" id="button1" disabled class="buttons">button1</button>
<button type="button" id="button2" class="buttons">button2</button>

</div>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
    $( document ).ready(function() {
  $( "#button1" ).click(function() {
    $("#button2").removeAttr('disabled');  
    $("#button1").attr('disabled','disabled');
  });
   $( "#button2" ).click(function() {
    $("#button1").removeAttr('disabled');  
    $("#button2").attr('disabled','disabled');
  });
});

</script>
相关问题