Frage

I am having trouble getting the link to be '(show)' or '(hide)' when I click on the link to either hide or show the paragraph text.

Here's the code I got that won't work:

var old_text = $(this).text();
var new_text = (old_text === '(hide)') ? '(show)' : '(hide)';
var toggle_link = $("<a href='#'> "+ new_text + "</a>");
$(this).after(toggle_link);
toggle_link.on('click', function (event){
  $(this).siblings('p').toggle();
});
$(this).after(toggle_link);

In the above code. I am toggling the show and hide link on and off, however the text isn't changing. It just remains ('hide').

War es hilfreich?

Lösung

Try this way:

var toggle_link = $("<a href='#'>(hide)</a>");
        $(this).after(toggle_link);
        toggle_link.on('click', function (event){
          $(this).siblings('p').toggle();
            var old_text = $(this).text();
            var new_text = (old_text === '(hide)') ? '(show)' : '(hide)';
            $(this).text(new_text);
        });

Andere Tipps

if you want to toggle between show and hiding text or link. Lets suppose you want to toggle the paragraph by clicking some link here its how you do it.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<a id="toggle" href="#" style="font-size:20px;">Click Me to show the Paragraph</a>
<p id="toggle1">This is the Paragraph for the sake of this demo. Click the above link to Hide me.</p>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>

        $("#toggle").click(function(){
        $("#toggle1").toggle('slow');
        });
</script>
</body>
</html>

I Hope this is what you want cuz your question is unclear..

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top