单击时切换按钮文本

时间:2013-11-28 19:39:49

标签: jquery html toggle

我有一个DIV(#newmsg),我使用带有按钮的jQuery隐藏:

<input type="button" id="hideshow" value="New Post">

这是jQuery代码:

jQuery(document).ready(function(){
    jQuery('#hideshow').live('click', function(event) {        
         jQuery('#newmsg').toggle('show');
    });
});

每当有人点击按钮时,我想将输入按钮的值从New Post切换到Cancel。我该怎么做?

3 个答案:

答案 0 :(得分:2)

要检查按钮的值,请使用.val()
不推荐使用.live(),请使用.on()
试试这个:

jQuery(document).ready(function(){
    jQuery(document).on('click', '#hideshow', function(event) {        
         if(jQuery(this).val() == 'New Post'){
             jQuery(this).val("Cancel");
         }
         else{
             jQuery(this).val("New Post");
         }
         jQuery('#newmsg').toggle('show');
    });
});

答案 1 :(得分:0)

尝试:

jQuery(document).ready(function(){
    jQuery('#hideshow').on('click', function(event) {        
         if(jQuery(this).val() == 'New Post'){
             jQuery(this).val("Cancel");
         }
         else{
             jQuery(this).val("New Post");
         }
         jQuery('#newmsg').toggle('show');
    });
});

答案 2 :(得分:0)

我在我的文件中有一个toggleText()函数,我已经为你调整了(你改变了值)。只需使用此代码:

//Copyright Karl-André Gagnon
jQuery.prototype.toggleText = function(t1, t2){
    var obj = {};
    obj[t1] = t2;
    obj[t2] = t1;
    return this.each(function(){
        $(this).val(obj[$(this).val()])
    })
}


jQuery(document).on('click', '#hideshow', function(event) {
    $(this).toggleText('New Post', 'Cancel');
    jQuery('#newmsg').toggle('show');
})

小提琴:http://jsfiddle.net/tt36q/8/