Question

Why doesn't this work? What would be a plausible solution to get this effect?

$(document).ready(function() {

  $('#myLink1').click(
    function() { 
      $('#myLink1').replaceWith('<a id="myLink2" href="#panel2">#panel2</a>');
    });

  $('#myLink2').click(
    function() { 
      $('#myLink2').replaceWith('<a id="myLink3" href="#panel3">#panel3</a>');
    });

});

I'm new to loops and how I'm supposed to add strings and variables.

$(document).ready(function() {
  var panelNum = 8;
  for (i=1;i<=panelNum;i++){
    $('#myLink'+i).click(function() { 
      $('#myLink'+i).replaceWith('<a id="myLink'+(i+1)+'" href="#panel'+(i+1)+'">#panel'+(i+1)+'</a>');
    });
  };
});
Was it helpful?

Solution

The problem is myLink2 doesn't exist until mylink is clicked. You have to add the mylink2 handler after it is created. Try the following:

function add_replace_with(i){
 $('#myLink'+i).click(
    function() {
     do_replace_with(i)
          return false;
    });
}
     function do_replace_with(i){
       $('#myLink'+i).replaceWith('<a id="myLink'+(i+1)+'" href="#panel'+(i+1)+'">#panel'+(i+1)+'</a>');

     $('#myLink'+(i+1)).click(
      function() {
        do_replace_with(i+1)
      });   
     }

$(document).ready(function() {
 add_replace_with(1);
});

I should note, that you might be better of hard-coding the links and just using .show() to toggle them.

OTHER TIPS

Alternatively:

$(function() {
  $('body')
    .delegate('#myLink1', 'click', function() {
      $(this).replaceWith('<a id="myLink2" href="#panel2">#panel2</a>');
    })
    .delegate('#myLink2', 'click', function() {
      $(this).replaceWith('<a id="myLin32" href="#panel3">#panel2</a>');
    })
  ;
 });

To generalize this for a whole bunch of such link, with similar naming convention:

$(function() {
  for (var link = 1; link < 8; ++link)
    (function(link) {
      $('body').delegate('#myLink' + link, 'click', function() {
        var nxt = link + 1;
        $(this).replaceWith('<a id="#myLink' + nxt + '" href="#panel' + nxt + '">panel ' + nxt + '</a>');
      });
    })(link);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top