用jQuery切换文本

时间:2013-04-29 10:11:22

标签: jquery text click toggle

我想将cta-end h1第一次点击的文字从Modification更改为close 然后,当你第二次点击时 - > close - > modification等等。 我希望文本切换。

这是我的HTML

    <div id="cta-end">
     <h1>Modification</h1>
    </div>

<div id="bloc1"><h3>BLOC 1</h3></div>
<div id="bloc2"><h3>BLOC 2</h3></div>

的jQuery

$(document).ready(function () {


    $('#cta-end').click(function () {
        $('#bloc1,#bloc2').toggle();
    });

});

我试图在堆栈上找到解决方案,但没找到..

这是demo

谢谢你:)

4 个答案:

答案 0 :(得分:4)

您可以使用:

 $('#cta-end').click(function () {
    $('#bloc1,#bloc2').toggle();
    $(this).children().text(($(this).children().text()=="Modification")?"close":"Modification");
});

答案 1 :(得分:2)

将您的事件处理程序更改为此处理程序,它应该可以正常工作。

 $('#cta-end').click(function () {
    $('#bloc1,#bloc2').toggle();
    if($('#bloc1').css("display") != "none"){
        $('#cta-end h1').text("Close");
    }
    else
    {
        $('#cta-end h1').text("Modification");
    }

});

答案 2 :(得分:1)

使用children()获取<h1>内的文字以及三元条件..

试试这个

 $('#cta-end').click(function () {
    $(this).children().text(($(this).children().text()=="Modification")?"close":"Modification");

     $('#bloc1,#bloc2').toggle();
});

fiddle here

答案 3 :(得分:1)

也许只是:http://jsfiddle.net/g4Rw5/6/

<div id="cta-end">
    <h1 class='toggle'>Modification</h1>
    <h1 class='toggle' style="display: none;">Close</h1>
</div>

然后将.toggle添加到您的选择器:

$('#cta-end').click(function () {
     $('#bloc1,#bloc2,.toggle').toggle();
});