javascript 单击时 jQuery 更改复选框按钮文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4853281/
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-10-25 15:06:08  来源:igfitidea点击:

jQuery change checkbox button text when clicked

javascriptjquerybuttoncheckbox

提问by Tanner Ottinger

I have some jQuery checkbox buttons, and they work fine. However, I would like to change their text upon a click. for example: the button's text is "click me". when the user clicks it, i needs to change to "thanks for clicking", for example.

我有一些 jQuery 复选框按钮,它们工作正常。但是,我想在单击时更改它们的文本。例如:按钮的文字是“点击我”。例如,当用户单击它时,我需要更改为“感谢单击”。

This is what I am trying using:

这就是我正在尝试使用的:

<script>
    $(function() {
        $("#button").button(); 
        $("#button").click(function(){
            if($("#label").is(':checked')) {
                $("#label span").text("Hide");
            }
            else {
                $("#label span").text("Show");
            }
        });
    }); 
</script>
<input id='button' type='checkbox' />
<label id='label' for="button">Show/Hide</label>

回答by Andy E

This is your first problem:

这是你的第一个问题:

       if($("#label").is(':checked')) {

<label>elements don't get "checked" only their checkboxes do. Change it to:

<label>元素不会被“检查”,只有它们的复选框才会被“检查”。将其更改为:

if (this.checked) {

In the code above, thisrefers to the checkbox element that has been clicked, and we're looking to see if the checkedproperty contains the value true. It's much more efficient that .is(':checked').

在上面的代码中,this指的是被点击的复选框元素,我们正在查看该checked属性是否包含值true。它的效率要高得多.is(':checked')

Also, the <label>element has no <span>child, it just has text, so

此外,该<label>元素没有<span>子元素,它只有文本,所以

            $("#label span").text("Hide");

should be

应该

            $("#label").text("Hide");

But you could shorten the whole thing using the ternary conditional operator:

但是您可以使用三元条件运算符缩短整个过程:

    $("#button").click(function(){
        $("#label").text(this.checked ? "Hide" : "Show");
    }

Working demo: http://jsfiddle.net/AndyE/qnrVp/

工作演示:http: //jsfiddle.net/AndyE/qnrVp/

回答by Darin Dimitrov

$("#button").click(function() {
    if($(this).is(':checked')) {
        $("#label").text("Hide");
    } else {
        $("#label").text("Show");
    }
});

And here's a live demo.

这是一个现场演示

回答by Andrey M.

Try this:

试试这个:

$("#button").click(function(){
     var th = $(this);
     if(th.is(':checked')) {
          $("label[for=" + th.attr('id') + "]").text("Hide");
     } else {
          $("label[for=" + th.attr('id') + "]").text("Show");
     }
});