Onclick event runs twice

后端 未结 1 1587
执念已碎
执念已碎 2021-01-25 04:24

I can\'t seem to work out why my onclick() event fires twice when the user clicks on a star.

If the user clicks on the first star in the first set, it shou

1条回答
  •  悲&欢浪女
    2021-01-25 05:06

    Problem with you code is that clicking on label in a fieldset emits click event on the input. So you really have two clicks - first on label, second - on related input radio.

    So, what you need to do is to track change event for radio instead tracking clicks on fieldset.

    Update: And as Temani Afif mentioned in comments, as you have non-unique ids for inputs, clicking on radio in second fieldset still gets value of input[type='hidden'] in first fieldset. So, you need to replace you labels ids too.

    More: a better practice for labels is wraping input in it, so you have markup something like:

    
    

    In this case you don't need id and for as label works with element which is inside it.

    $(document).on('change', 'input[type="radio"]', function (e) {
        console.log(
            $(this).val(), 
            $(this).parent().find("input[type='hidden']").val()
        );
    });
    fieldset,
    label {
      margin: 0;
      padding: 0;
      margin-bottom: 20px;
    }
    
    .rating {
      border: none;
      float: left;
    }
    
    .rating>input {
      display: none;
    }
    
    .rating>label:before {
      margin: 5px;
      font-size: 1.25em;
      font-family: FontAwesome;
      display: inline-block;
      content: "\f005";
    }
    
    .rating>.half:before {
      content: "\f089";
      position: absolute;
    }
    
    .rating>label {
      color: #ffffd;
      float: right;
    }
    
    .rating>input:checked~label,
    
    /* show gold star when clicked */
    
    .rating:not(:checked)>label:hover,
    
    /* hover current star */
    
    .rating:not(:checked)>label:hover~label {
      color: #FFD700;
    }
    
    
    /* hover previous stars in list */
    
    .rating>input:checked+label:hover,
    
    /* hover current star when changing rating */
    
    .rating>input:checked~label:hover,
    .rating>label:hover~input:checked~label,
    
    /* lighten current selection */
    
    .rating>input:checked~label:hover~label {
      color: #FFED85;
    }
    
    
    
    


    0 讨论(0)
提交回复
热议问题