从text()更改回原始文本

时间:2016-03-09 20:11:23

标签: jquery

我正在使用jQuery更改单击元素上的文本。 但是如何将文本更改回原始文本?

$(".myClass").click(function() {
        $(this).text("You clicked me!");
    });

我希望能够再次点击.myClass并获取原始文字...是否有与text()“切换”相似的内容?

3 个答案:

答案 0 :(得分:1)

我已经写了一个扩展来解决这个问题。它只有几行:

jQuery.fn.extend({
    toggleText: function(stateOne, stateTwo) {
        return this.each(function() {
            stateTwo = stateTwo || '';
            $(this).text() !== stateTwo && stateOne ? $(this).text(stateTwo) : $(this).text(stateOne);
        });  
    }
});

用法:

$('.myClass').on('click', function() {
    $(this).toggleText('show', 'hide'); //Toggles from hide to show
});

答案 1 :(得分:0)

将原始文本存储在变量中,然后在它们之间切换。

答案 2 :(得分:0)

更改字段文本后,原始文本消失。您需要在某处存储该值。隐藏字段可以工作,或变量。取决于您何时想要切换回原始文本。