【问题标题】:Label fires click function twice标签触发点击功能两次
【发布时间】:2010-11-16 11:42:16
【问题描述】:

有什么方法可以调用函数,同时通过点击标签来保存单选按钮的效果?

示例(我需要通过单击单选按钮的标签来打开/关闭带有复选框的字段集)

渡//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


点击标签

标签: jquery click label


【解决方案1】:

e.preventDefault(); 的问题是它会阻止标签点击检查单选按钮。

更好的解决方案是简单地添加一个“已检查”快速检查,如下所示:

$("label").click(function(e){
  var rbtn = $(this).find("input");
  if(rbtn.is(':checked')){
    **All the code you want to have happen on click**
  }
)};

【讨论】:

    【解决方案2】:

    改为使用单选按钮上的焦点事件。

    试试这个:

    <script type="text/javascript">
        $(function(){ 
            accordionOptions();
        });
        var accordionOptions = function(){
            $("label.legend > input, label.childless > input").focus(function(event) {
                var el = $(this).parent();
                var opposites = $(".subtype").not(el.next());
                opposites.find("input:checked").attr("checked", false);
                opposites.removeClass("expanded");
                el.siblings("label").removeClass("expanded");
                el.next(".subtype").toggleClass("expanded");
                el.toggleClass("expanded");
            });
        }
    </script>
    

    【讨论】:

    • 谢谢,杰森。我重复之前的解决方案。这个很酷。但在这种情况下 label 和 next fieldset.subtype 的属性 toggleClass 无效。如果我们将新的设计规则添加到 .expanded 类中(例如 .expanded { display: block !important; background: #FCC}),将会很明显。
    【解决方案3】:
    - $("label.legend, label.childless").click( function(event){
    + $("label, input").click( function(event){
    

    ...然后是一些化妆品来保持无线电标签的位置。

    【讨论】:

    • 谢谢,安德烈斯。这是很酷的解决方案。但在这种情况下 label 和 next fieldset.subtype 的属性 toggleClass 无效。如果我们将新的设计规则添加到 .expanded 类中(例如 .expanded { display: block !important; background: #FCC}),将会很明显。
    【解决方案4】:

    这对我有用:

    $("label.legend, label.childless").click( function(event){
      var opposites = $(".subtype").not($(this).next());
      var el = $(this);
      opposites.find("input:checked").removeAttr('checked');
      opposites.removeClass("expanded");
      el.siblings("label").removeClass("expanded");
      el.next(".subtype").addClass("expanded");
      el.toggleClass("expanded");
    });    
    

    正在用 toggleClass 交换 addClass。

    【讨论】:

      猜你喜欢
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 2012-08-25
      • 2023-03-17
      • 1970-01-01
      • 2018-01-18
      • 1970-01-01
      • 2018-03-26
      相关资源
      最近更新 更多