6

Possuo o seguinte exemplo feito em JavaScript, do qual é um texto escrito "See more", que ao clicar nele ele você é possibilitado de ver mais texto:

Exemplo no JSFiddle

Código

<head>
  <title>
    Javascript demo - expand/collapse text
  </title>
  <script language="JavaScript" type="text/javascript">
    // for displaying or hiding parts of the page
    function blocking(nr) {
      displayNew = (document.getElementById(nr).style.display == 'none') ? 'block' : 'none';
      document.getElementById(nr).style.display = displayNew;
    }
  </script>
</head>

<!-- initially hide the contents of whatItIs and background -->
<body onload="blocking('whatItIs'); blocking('background');">
  <a href="" onclick="blocking('whatItIs'); return false;">See more...</a>
  <br><br>
  <div id="whatItIs">
    Pardus is a GNU/Linux distribution developed in Turkey, as a product of the Pardus Project. It was named after the Anatolian Leopard.
    <br><br>
    Pardus is an easy-to-install and -use operating system, with many enhancements to desktop usability, compatibility and security. With Pardus 1.0 (and the now-released Pardus 2007 version), users can connect to Internet, read e-mails, securely communicate with others and exploit the computer's multimedia capabilities by listening to music and watching movies.
    <br><br>
    Ladislav Bodnar, the creator of DistroWatch, wrote in his round-up of Linux/*nix in 2006 that Pardus is one of the distros he was most impressed by this year "...thanks to unique package management ideas, innovative start-up sequence and general desktop polish..."
    <br><br>
    Pardus is open source and freely distributed as a GPL (General Public License) product. It can be installed in Turkish, English, Spanish, German or Dutch.
    <br><br>
  </div>
</body>

Mas tenho uma questão, quando clico em "See more" o texto é mostrado, até aí tudo bem.

Pergunta

O código que tenho está a funcionar, mas eu gostaria que ao clicar em "See more", o texto mudasse para "Hide" no lugar de "See more". Como atingir este objectivo?

4 Respostas 4

5

Podes utilizar a função .text() (Inglês) do JQuery.

Fiz um JSFiddle para veres como funciona, onde no mesmo estou a alterar o texto do elemento HTML com o id="see":

if ($("#see").text() == "See more...")
{
    $("#see").text("hide");
}
else {
    $("#see").text("See more...");
}

Exemplo no JSFiddle para uso do .text()

1

Para o caso de pretenderes manter o anonimato do elemento que recebeu o clique, podes passar o mesmo para dentro da função blocking, e a partir dai verificar e atualizar o texto do mesmo em conformidade:

Exemplo a funcionar no JSFiddle

JavaScript

function blocking(nr, e) {

    // trocar texto
    if (typeof e !== 'undefined' && e!='') {
        e.innerHTML = (e.innerHTML=='See more...') ? 'Hide' : 'See more...';
    }

    displayNew = (document.getElementById(nr).style.display == 'none') ? 'block' : 'none';
    document.getElementById(nr).style.display = displayNew;
}

HTML

<a href="" onclick="blocking('whatItIs', this); return false;">See more...</a>

Explicação

  1. No atributo onclick, estamos a passar um segundo parâmetro this, que representa o elemento em si.

    onclick="blocking('whatItIs', this); return false;"
    
  2. Na função blocking recebemos o elemento na variável e.

    function blocking(nr, e)
    

    Verificamos se a mesma está definida e não é vazia pois na tag body estás a chamar a função para esconder o texto ao inicio.

    if (typeof e !== 'undefined' && e!='') {
    
  3. Numa só linha fazemos a actualização do texto, verificando o atual.

    e.innerHTML = (e.innerHTML=='See more...') ? 'Hide' : 'See more...';
    
1

Além da opção dada pelo @CesarMiguel, se deseja usar apenas JavaScript, você pode fazer assim:

function blocking(nr, click) {
    var elementStyle = document.getElementById(nr).style.display;
    var displayNew = 'none';
    var text = 'See more...';
    if (elementStyle == 'none') {
        displayNew = 'block';
        text = 'Hide text';
    }
    document.getElementById(nr).style.display = displayNew;
    document.getElementById(click).innerHTML = text;
}

Exemplo no JSFiddle

0
0

Você pode utilizar o .html() também caso queria colocar marcadores HTML. A deferença entre .html() e .text() é que o primeiro aceita tags HMLT e XML. Já o segundo vai converter as tags HMLT para textos.

Exemplo

$(this).html('<a href="example.html">Link</a><b>hello</b>')

O resultado do script acima seria Exatamente o texto descrito:

<a href="example.html">Link</a><b>hello</b>

Agora com o outro exemplo

$(this).text('<a href="example.html">Link</a><b>hello</b>')

Já o resultado do script acima seria

&lt;a href="example.html"&gt;Link&lt;/a&gt;&lt;b&gt;hello&lt;/b&gt;

Com escapes

Credito da explicação

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .