0

我正在尝试使用按钮作为开关。如果我单击按钮valueid更改。如果我再次单击该按钮,它会回到原来的状态value并且id.

原始值可能如下所示:

value="Show all" id="showall"

更改为此值

value="Standard" id="default"
<script>
    $(function () {
        $("#showall").click(function () {
            $("#showall") //  change the Value text to Standard on the button
            $("#showall") // Change ID value to default on the button
        });
        $("#default").click(function () {
            $("#default") // change value back to the original which is "Show all"
            $("#default") // change ID back to original which is "Showall"
        });
</script>
4

6 回答 6

1

假设这个按钮<div class="container"></div>在我们可以处理它的事件的某种类型的范围内(你可以从正文或文档中处理它,尽管不建议这样做):

$(".container").on("click", "#showall, #default", function(){
  var props = this.id === "showall" 
      ? { value:'Standard', id:'default' } 
      : { value:'Show All', id:'showall' };
  $(this).attr( props );
});

演示:http: //jsbin.com/eravoq/2/edit

于 2012-05-14T14:55:23.160 回答
0
   $("#showall").on('click', function () {
        $(this).attr({ 'value': 'Standard', 'id': 'default' });
    });

    $("#default").on('click', function () {
        $(this).attr({ 'value': 'Show all', 'id': 'showall' });
    });
于 2012-05-14T14:59:05.250 回答
0

为什么要更改按钮的 ID?你可以做这样的事情:

  $(function () {
       $("#switchButton").click(function(){
           if($(this).value == "default"){
                $(this).value = "Show all";
                // do other stuff
           }else if($(this).value == "Show all"){
                $(this).value = "default";
                // do other stuff
           }
       });
    });
于 2012-05-14T15:01:08.090 回答
0
$("#showall").on('click', function() {
    this.id = this.id=='showall' ? 'default' : 'showall';
    this.value = this.value=='Standard' ? 'Show All' : 'Standard';
});

小提琴

于 2012-05-14T15:03:20.487 回答
0

我知道这不完全是您要问的,但是如果我们退后一步回答您的问题,我认为您真正想要的是在两个按钮之间切换,因此我认为这是非常可维护,易于理解,直观的,还有很多更多的事情要做有两个结构良好的按钮,然后显示/隐藏:

<style>
  button#default{
    display: none;
  }
</style>
 ​
<button id="showall" value="Show all">Show all</button>
<button id="default" value="Standard">Standard</button>

<script>
  function toggleButtons(){
    $("button#showall, button#default").toggle();
  }

  $("button#showall, button#default").click( toggleButtons );
</script>

检查 jsFiddle

于 2012-05-14T15:04:14.520 回答
0

您应该使用类切换而不是更改 ID。

http://jsfiddle.net/JzMnM/

if (that.hasClass('foo')) {
    that.removeClass('foo').addClass('bar').val('bar');
} else {
    that.removeClass('bar').addClass('foo').val('foo');
}
于 2012-05-14T15:10:06.473 回答