如何使用jquery替换单击按钮

时间:2013-07-29 12:25:36

标签: javascript jquery html

我目前有一个ID为

的按钮
<input type="button" id="show_button"  value="Show" />

我想要的是......点击按钮,按钮的值将更改为“隐藏”,它的ID将更改为“hide_button”..点击隐藏按钮时,它的值将更改为“显示”,它的ID将变为“show_button”..我怎样才能实现这一点?

6 个答案:

答案 0 :(得分:5)

我不知道您为什么要更改ID,因为我们可以在不更改ID的情况下获得您想要的内容。 试试这个

 $('#show_button').click(function(){
     var $this=$(this);
     $this.val(($this.val()=="Show")?"Hide":"Show");
 });

这样做更好,因为您不必为两个ID使用两个单击事件处理程序。

如果你需要更改ID,那么请使用事件委托...

 $(document).on('click','#show_button',function(){
     var $this=$(this);
     $this.prop('id','hide_button');
     $this.val("Hide"); //OR  $this.val("Hide") //if you are using input type="button"
 });

$(document).on('click','#hide_button',function(){
     var $this=$(this);
      $this.prop('id','show_button');
     $this.val("Show"); //OR  $this.val("Hide") //if you are using input type="button"
 });

fiddle here

答案 1 :(得分:1)

您可以使用

更改值
  $('#show_button').val('hide');

您可以使用

更改ID
 $('#show_button').attr('id','hide_button');

答案 2 :(得分:1)

使用Jquery Javascript库:

$('body').on('click', '#show_button', function() {
  $(this).attr('id', 'hide_button').val('Hide');
});

$('body').on('click', '#hide_button', function() {
  $(this).attr('id', 'show_button').val('Show');
});

答案 3 :(得分:1)

$('body').on('click', '#show_button, #hide_button', function() {
    var $this = $(this),
        isShow = $this.attr('id') == 'show_button';

    if (isShow) {
        $this.attr('id', 'hide_button').val('Hide');
    }
    else {
        $this.attr('id', 'show_button').val('Show');
    }
});

jsFiddle:http://jsfiddle.net/sW49u/

答案 4 :(得分:1)

您的问题的一个解决方案是有两个输入,您可以在它们之间切换。我不想改变/重命名id的原则。

选中 demo

html

<input type="button" id="show_button"  value="Show" />
<input type="button" id="hide_button"  value="Hide" style="display:none;" />

jQuery

$('input').click(
    function(){
       $('input').toggle();
});

答案 5 :(得分:1)

工作示例:http://jsfiddle.net/TjaBR/

$('body').on('click', '#process', function() {
   $(this).toggleClass('hidden');
   $(this).val($(this).hasClass('hidden') ? 'Hide' : 'Show');
});