【问题标题】:Doing mutual exclusive checkbox of two buttons with siblings()用兄弟姐妹()做两个按钮的互斥复选框
【发布时间】:2018-05-16 02:05:57
【问题描述】:

我正在尝试获得两个带有互斥复选框的按钮组。

这是我在 JS Fiddle 上的当前结果

如您所见,有四个 div(id="UserVsComputer"id="User1VsUser2"id="PlayableHits"id="button-new-game")。

当我们点击相关<input>的复选框(即对应右侧的<div>)时,我希望前两个<div>UserVsComputerUser1VsUser2)互斥。

在 JavaScript 部分,我做了:

// Select the clicked checkbox for game type                                          
   $('input.game').on('click',function(){                                                
     setGameType();
   }); 
       
   function setGameType() {
   // Get state of the first clicked element 
   var element = $('#UserVsComputer input.game');
   var checkBoxState = element.prop('checked');
   // Set !checkBoxState for the sibling checkbox, i.e the other
   element.siblings().find('input.game').prop('checked',!checkBoxState);
   updateGameType();
   }
  
   function updateGameType() {
   // Set type of game
   if ($('#UserVsComputer input').prop('checked'))
     gameType = 'UserVsComputer';
   else
     gameType = 'User1VsUser2';
   }

我不希望<div id="PlayableHits" class="checkbox"> 担心前两个复选框的互斥。

例如,下面的捕获显示我可以将前两个复选框设置为 true 而不使它们独占:

这里可能有什么问题?

【问题讨论】:

  • 检查你的element - 它是复选框,所以你正在寻找它的兄弟姐妹,而不是包含DIV

标签: javascript jquery html css twitter-bootstrap


【解决方案1】:

尝试以下操作 - 它使用点击事件的目标来确定选中了哪个复选框:

// Select the clicked checkbox for game type
$('input.game').on('click',function(e){
  setGameType(e.target);
});

function setGameType(cb) {
  var container = $(cb).parent().parent();
  var checkBox = $(cb);
  var checkBoxState = checkBox.prop('checked');

  // Set !checkBoxState for the sibling checkbox, i.e the other
  container.siblings().find('input.game').prop('checked', !checkBoxState);
  updateGameType();
}

function updateGameType() {
  // Set type of game
  if ($('#UserVsComputer input').prop('checked')) {
    gameType = 'UserVsComputer';
  } else {
    gameType = 'User1VsUser2';
  }
}

还有其他一些可能需要注意的位(硬编码的.parent().parent() 并不漂亮,但在这种情况下可以使用..

【讨论】:

  • -@Forty3 感谢您的回答。最后一个问题,cb$(cb) 之间有什么区别:我意识到我无法使用 cb.prop('checked') 访问复选框状态,但我可以使用 $(cb).prop('checked '), 为什么 ?问候
  • cb 获取 e.target 的值,这是一个简单的 DOM 元素,而不是 jQuery 对象。将其包装在 $() 中会将其转换为 jQuery 对象,从而使其具有 .prop() 可用性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
  • 2011-01-09
  • 1970-01-01
  • 1970-01-01
  • 2012-07-23
相关资源
最近更新 更多