【问题标题】:Prevent parent category radio button from being clicked防止单击父类别单选按钮
【发布时间】:2017-05-30 18:09:05
【问题描述】:

我有这个函数/脚本可以将复选框转换为单选按钮(在类别元框中),但我需要稍微扩展一下功能,但我不确定如何去做。

脚本:

function convert_root_cats_to_radio() {
    global $post_type;
?>
<script type="text/javascript">
jQuery("#categorychecklist>li>input").each(function(){
    this.disabled = "disabled";
});
jQuery("#categorychecklist>li>ul>li>input").each(function(){
    this.disabled = "disabled";
});
jQuery("#categorychecklist>li>label input").each(function(){
    this.type = 'radio';
});
jQuery("#categorychecklist>li>ul>li>label input").each(function(){
    this.type = 'radio';
});
// Hide the 'most used' tab
jQuery("#category-tabs li:odd").hide();
</script> <?php
}
add_action( 'admin_footer-post.php',     'convert_root_cats_to_radio' );
add_action( 'admin_footer-post-new.php', 'convert_root_cats_to_radio' );

现在需要做的是:防止用户选择父类别。

例如,在下面显示的图像中,您应该能够选择除 Bandicoot 之外的任何内容,因为 Bandicoot 是父级(它有子级)。哦,并且允许选择 Bandicoot 的子项。

所以规则应该是:如果你是父母,你不能被选中,但你的孩子可以。

【问题讨论】:

  • 你能分享这部分渲染的 html 吗?将有助于查看遍历。

标签: javascript jquery wordpress function categories


【解决方案1】:

取决于您的输出 html 的外观,您可以使用以下选项之一:

jQuery("#categorychecklist > li > ul").each(function(){
    jQuery(this).parent('li').children('label').children('input').attr('disabled', true);
});

或:

jQuery("#categorychecklist > li > ul").each(function(){
    jQuery(this).prev('label').children('input').attr('disabled', true);
});

或者更好的是,删除收音机:

jQuery("#categorychecklist > li > ul").each(function(){
    jQuery(this).prev('label').children('input').remove();
});

【讨论】:

  • Bravo - 完美运行。我选择保持收音机可见,以便用户可以看到(有限的)层次结构。
【解决方案2】:

请查看脚本代码中的注释。

$(function() {
  $('input[type=radio]').on('click', function() {
    //assumes that radio button > wrapped around a label > wrapped around li 
    var liObj = $(this).parent().parent();
    if (liObj != undefined && $(liObj).is('li') && $(liObj).has('ul').length > 0) {
      return false;
    }
  });
})
ul {
  list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id='test'>
  <li>
    <label>
      <input type='radio' name='cat' />1</label>
  </li>
  <li>
    <label>
      <input type='radio' name='cat' />2</label>
  </li>

  <li>
    <label>
      <input type='radio' name='cat' />3</label>
    <ul>

      <li>
        <label>
          <input type='radio' name='cat' />3-1</label>
      </li>
      <li>
        <label>
          <input type='radio' name='cat' />3-2</label>

        <ul id='test'>
          <li>
            <label>
              <input type='radio' name='cat' />3-2-1</label>
          </li>
          <li>
            <label>
              <input type='radio' name='cat' />3-2-2</label>
          </li>
        </ul>



      </li>
    </ul>

  </li>


</ul>

【讨论】:

    猜你喜欢
    • 2018-01-23
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 2016-02-12
    • 2012-12-06
    相关资源
    最近更新 更多