2012-05-14 74 views
0

我想用一个按钮作为开关。如果我点击按钮valueid的变化。如果我再次点击该按钮,它会回到原来的valueid点击按钮更改按钮上的ID值,点击新的ID改回原来的ID与Jquery

原始值可能看起来像这样:

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> 
+0

你应该切换改变ID的类代替。 – jbabey

回答

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

+0

不要忘记提交的初始值;)+1 –

0
$("#showall").on('click', function() { 
     $(this).attr({ 'value': 'Standard', 'id': 'default' }); 
    }); 

    $("#default").on('click', function() { 
     $(this).attr({ 'value': 'Show all', 'id': 'showall' }); 
    }); 
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 
      } 
     }); 
    }); 
0
$("#showall").on('click', function() { 
    this.id = this.id=='showall' ? 'default' : 'showall'; 
    this.value = this.value=='Standard' ? 'Show All' : 'Standard'; 
}); 

FIDDLE

0

我知道是不是你问什么,但如果我们走了一步回到你的问题,我想你真正想要的是来toggle两个按钮之间,所以我认为是非常易于维护,可以理解,直观和很多更多的事情,只是有两个良好形成的按钮,然后显示/隐藏然后交替:

<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> 

Check the jsFiddle

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'); 
}