1

我有一个简单的任务是在按下按钮后更改按钮上的文本。这是我的脚本:

$(".recent").on("click", 'button', function () {
        $(this).closest($("li")).find($(".content")).slideToggle();
        if ($(this).text="Show content") {
            $(this).text("Hide content");
        } else {
            $(this).text("Show content");
        }
    });

当我按下按钮时,文本变为“隐藏内容”。但是当我再次按下按钮时,它不会变回“显示内容”。猜猜这是关于一些简单的事情......将不胜感激。

4

4 回答 4

4

您需要使用等价===而不是赋值=并使用 text() 而不是 text

$(".recent").on("click", 'button', function () {
        $(this).closest($("li")).find($(".content")).slideToggle();

        if ($(this).text() === "Show content") {
            $(this).text("Hide content");
        } else {
            $(this).text("Show content");
        }
    });
于 2013-03-14T17:46:02.580 回答
2

用于===比较。您使用的是=哪个分配值。也是.text()一种方法

$(".recent").on("click", 'button', function () {
    $(this).closest('li').find('.content').slideToggle();
    if ($(this).text() === "Show content") {
        $(this).text("Hide content");
    } else {
        $(this).text("Show content");
    }
});
于 2013-03-14T17:45:55.370 回答
1

.text()是一个方法,所以你必须调用它来获取和设置文本:

$(".recent").on("click", 'button', function() {
    var $this = $(this);

    $this.closest("li").find(".content").slideToggle();

    if ($this.text() === "Show content") {
        $this.text("Hide content");
    } else {
        $this.text("Show content");
    }
});
于 2013-03-14T17:47:30.467 回答
1

the.text是一种方法,因此需要跟在 a 之后()。此外,对于相等,使用== not =, single=用于分配。

试试这个:

$(".recent").on("click", 'button', function () {
    $(this).closest($("li")).find($(".content")).slideToggle();
    if ($(this).text() == "Show content") {
        $(this).text("Hide content");
    } else {
        $(this).text("Show content");
    }
});
于 2013-03-14T17:47:44.220 回答