jQuery:点击时更改按钮文字

时间:2013-10-14 17:02:18

标签: jquery

在看到Toggling button text in jquery这个问题后,我尝试在我的情况下重新创建它,但似乎无法让它发挥作用。

以下是我所做过的事情:http://jsfiddle.net/V4u5X/

$('.SeeMore2').click(function(){
    var $this = $(this);
    $this.toggleClass('SeeMore');
    if($this.hasClass('.SeeMore2')){
        $this.text('See More');         
    } else {
        $this.text('See Less');
    }
});

似乎只运行一次if语句。我错过了什么?

6 个答案:

答案 0 :(得分:37)

$('.SeeMore2').click(function(){
    var $this = $(this);
    $this.toggleClass('SeeMore2');
    if($this.hasClass('SeeMore2')){
        $this.text('See More');         
    } else {
        $this.text('See Less');
    }
});

这应该这样做。你必须确保切换正确的类并取出“。”来自hasClass

http://jsfiddle.net/V4u5X/2/

答案 1 :(得分:6)

试试这个, 这个javascript代码可以随时更改文本以单击按钮。http://jsfiddle.net/V4u5X/2/

html代码

<button class="SeeMore2">See More</button>

的javascript

$('.SeeMore2').click(function(){
        var $this = $(this);
        $this.toggleClass('SeeMore2');
        if($this.hasClass('SeeMore2')){
            $this.text('See More');         
        } else {
            $this.text('See Less');
        }
    });

答案 2 :(得分:2)

  

其工作短代码

$('.SeeMore2').click(function(){ var $this = $(this).toggleClass('SeeMore2'); if($(this).hasClass('SeeMore2')) { $(this).text('See More');
} else { $(this).text('See Less'); } });

答案 3 :(得分:1)

这应该适合你:

    $('.SeeMore2').click(function(){
        var $this = $(this);
        $this.toggleClass('SeeMore2');
        if($this.hasClass('SeeMore2')){
            $this.text('See More');         
        } else {
            $this.text('See Less');
        }
});

答案 4 :(得分:1)

在HTML中:

[0]

在Jquery中编写此函数:

<button type="button" id="AddButton" onclick="AddButtonClick()" class="btn btn-success btn-block ">Add</button> 

答案 5 :(得分:0)

使用:

 const { mutateAsync } = useMutation(async (settings: UserSettings) => {
        const updateRequest = new VoidPostRequest<UserSettings>("/UserSettings/Update");
        await updateRequest.post(settings);
        return settings;
    }, {
        onSuccess: (newData) => {
            queryClient.setQueryData(userSettingsQueryClientKey, newData);
            queryClient.refetchQueries(userSettingsQueryClientKey);// this is new

        }
    })