Javascript 点击标签不会触发点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28029880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:07:49  来源:igfitidea点击:

Clicking on label doesn't trigger click event

javascriptjquery

提问by Andrey

I have this code:

我有这个代码:

<label><input type="checkbox">True?</label>

and

$("label").click(function () {
  $(this).toggleClass("active");
});

When I click the checkbox class toggles, when I click "True?" nothing happens. Why?

当我点击复选框类切换时,当我点击“是吗?” 没发生什么事。为什么?

Then if I don't wrap checkbox in label everything works fine.

然后,如果我不将复选框包装在标签中,一切正常。

<input type="checkbox" id="c1"><label for="c1">True?</label>

This is so weird... And it doesn't matter if I put "for" or not.

这太奇怪了......我是否输入“for”都没有关系。

http://jsfiddle.net/zufs6ueh/1/

http://jsfiddle.net/zufs6ueh/1/

What is going wrong here?

这里出了什么问题?

采纳答案by rwacarter

This would be safer to use:

这将更安全地使用:

$(function() {

    $('input[type="checkbox"]').bind('change', function (v) {

        if($(this).is(':checked')) {
            $(this).parent().addClass('active');
        } else {
            $(this).parent().removeClass('active');
        }
    });

});

Using changeinstead of clickallows for people that navigate forms using the keyboard.

使用change代替click允许人们使用键盘导航表单。

回答by Moob

Clicking the label also triggers a click on the input so bind the change event to the checkbox itself:

单击标签还会触发对输入的单击,因此将更改事件绑定到复选框本身:

$(function(){
    $("label input").on("click",function(){
 $(this).parent().toggleClass("active");
    });
});
.active {color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label><input type="checkbox" />True?</label>

Or With CSS 3

或使用 CSS 3

If you don't need to support old browsers, you could use the :checkedpseudo-class in CSS instead:

如果您不需要支持旧浏览器,您可以使用:checkedCSS 中的伪类代替:

input[type=checkbox]:checked + label {color:red;}
<input type="checkbox" id="demo" name="demo"> 
<label for="demo">True?</label> 

回答by S0AndS0

You're really close @Andrey, some noteworthy things about HTML inputs;

你真的很接近@Andrey,关于 HTML inputs 的一些值得注意的事情;

  • Both radioand checkboxHTML typescan have an onclickcall out to JavaScript

  • Both radioand checkboxHTML typeshave the .checkedproperty that maybe inspected by JavaScript and the :checkedpseudo class within CSS

  • Using nameson radioHTML typesallows for groupingthings

  • 无论radiocheckboxHTMLtype小号可以有一个onclick通话中的JavaScript

  • 无论radiocheckboxHTMLtype小号.checked,也许由JavaScript检查属性和:checkedCSS中的伪类

  • 使用name小号radioHTMLtype小号允许分组东西

Here's some example code that does stuffwith a checkbox...

下面是做一些示例代码的东西checkbox...

/**
 * Example JavaScript function for HTML input radio or checkbox types to call
 * @returns {boolean}
 */
function checkCheckbox(checkbox) {
  if (checkbox.checked != true) return false;
  /* Do JavaSript things when checkbox is checked */
  console.log('checkbox.checked -> ' + checkbox.checked);
  window.alert('checkbox.value -> ' + checkbox.value);
  return true;
}
/**
 * Hide things that should not be seen by just anyone
 */
.menu__checkbox,
.menu__container {
  display: none;
  visibility: hidden;
  opacity: 0;
  filter: alpha(opacity=0); /* Old MS compatibility */
}

/**
 * Stylize the label some
 */
.menu__label {
  display: block;
  width: 20px;
  height: 100%;
  transform: rotate(90deg);
}


/**
 * Show some things when checkbox is checked
 * Note, if feeling adventurous try using a `~` instead of `+`
 */
.menu__checkbox:checked + .menu > .menu__container {
  display: block;
  visibility: visible;
  opacity: 1;
  filter: alpha(opacity=100);
}

/**
 * Oh and un-rotate label when checkbox is checked too
 */
.menu__checkbox:checked + .menu > .menu__label {
  transform: rotate(0deg);
}
<input type="checkbox"
       class="menu__checkbox"
       value="valuable_checkbox"
       onclick="checkCheckbox(this);"
       id="trigger-menu">


<div class="menu">

  <div class="menu__container">
    <p class="menu__description">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
      proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
  </div>

  <label for="trigger-menu"
         class="menu__label">
         &#x25B2;
  </label>

</div>

... if ya look real close, targetingvia trigger-menushared between the above label'sforand the input'sidis doing some things with CSS and HTML that many might resort to JavaScript to do... though placing the checkbox so far outside of the menu's scope was only for demonstration; just 'cause something canbe done doesn't always mean shouldin other words.

...如果你看起来真的很接近,通过在上述's's之间共享的目标正在使用 CSS 和 HTML 做一些事情,许多人可能会求助于 JavaScript 来做...尽管将复选框放置在菜单之外范围仅用于演示;换句话说,因为可以做某事并不总是意味着应该trigger-menulabelforinputid

Like I eluded to the question's code was really close...

就像我逃避问题的代码非常接近......

<input type="checkbox" id="c1"><label for="c1">True?</label>

... probably would be functional with...

...可能会与...一起使用

<input id="c1" type="checkbox" onclick="window.alert('this.checked -> ' + this.checked);">
<label for="c1">Is checked?</label>

And as I also hinted that radiotypedinputscould be use similarly, the following is a preview of something that may be made public one day within something ridiculous...

当我还暗示,radiotypedinput小号可以使用同样,以下是一些预览可以公开总有一天会有可笑的内...

    <div class="menu__style">
      <input type="radio"
             name="colorize"
             value="Default"
             onclick="color_picker.unsetAlternateStyleSheet()"
             class="menu__style__item"
             id="style-default">
      <label for="style-default"
             class="menu__style__label">Default Style</label>
      <br>

      <input type="radio"
             name="colorize"
             value="AlternateStyleOne"
             onclick="color_picker.setAlternateStyleSheet(title = this.value)"
             class="menu__style__item"
             id="style-one">
      <label for="style-one"
             class="menu__style__label">First Alternative Style</label>
      <br>

      <input type="radio"
             name="colorize"
             value="AlternateStyleTwo"
             onclick="color_picker.setAlternateStyleSheet(title = this.value)"
             class="menu__style__item"
             id="style-two">
      <label for="style-two"
             class="menu__style__label">Second Alternative Style</label>
    </div>