开发者

Multiple replaceWiths in jQuery?

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

$(d开发者_Python百科ocument).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>');
    });
  };
});


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.


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);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜