0

我的页面上有一个按钮

 <button id="show1" class="morelinkblack">Find Out More</button>

当点击它运行此代码

 $("#show1").click(function(){
   $(".hidden-div1").slideToggle("slow");
 });

有没有办法在 div 可见时将文本更改为“关闭”而不是“了解更多”?

4

3 回答 3

7

你可以做:

$("#show1").click(function(){
    var that = $(this);
    $(".hidden-div1").slideToggle("slow", function() {
        if ($(this).is(":visible")) {
            that.text("Close");
        } else {
            that.text("Find out more");
        }
    });
});

根据评论,可以打开或关闭 div,具体取决于用户来自何处。对 DOM 就绪的简单检查可以相应地设置文本:

$(".hidden-div1").is(":visible") ? $("#show1").text("Close") : $("#show1").text("Find out more");
于 2013-07-01T15:10:22.223 回答
1

也许这个:

$("#show1").click(function () {
    var $div = $(this);
    $(".hidden-div1").slideToggle("slow").promise().done(function () {
        $div.text(function () {
            return $(this).is(":visible") ? "Close" : "Find Out More"
        });
    });
});
于 2013-07-01T15:19:21.520 回答
1

更新代码

$("#show1").click(function() {
    var el = $(this);
    $(".hidden-div1").slideToggle("slow", function() {
        if ($(this).css('display') == 'none') { // <- Updated here to check if div is close or open
            el.text('Find Out More');
        } else {
            el.text('Hide More');
        }
    });
});

更新文档就绪/页面加载上的按钮文本

$(document).ready(function() {
    if ($(".hidden-div1").css('display') == 'none') {
        $("#show1").text('Find Out More');
    } else {
        $("#show1").text('Hide More');
    }
});
于 2013-07-01T15:11:50.330 回答