jquery passing $(this) to other functions

2020-04-17 06:29发布

问题:

High!

What i want to do is the following: i have a table with a onclick attached to a link that resides in the table of an even row. every odd row is hidden. on a click on that link, the odd row is shown and data is loaded into that row. Works fine

Now what i want to do is that whenever that process is done, i want to attach a new click function to that link that makes the row hidden again. Kind of like toggle, but then with some more then just show/hide functionality. I tried to do that with the following code, but cant get it to work.

I surely miss something very basic or just do not know jquery well enough (which is very well possible, because i just got started for a few weeks ago).

$(document).ready(function(){

    // The version icons
    $("a.version").click(function () {
        var sLink = $(this).attr("href");
        var nexttr = $(this).parent().parent().next("tr.version");
        var nexttrtd = nexttr.find("td:first");
        $.get(sLink, function(sData){
            nexttrtd.html(sData);
            nexttr.show();
        });

        $(this).click(function(){
            attachHideMyChildren();
        });

        return false;
    });
});

function attachShowMyChildren()
{
    var sLink = $(this).attr("href");
    var nexttr = $(this).parent().parent().next("tr.version");
    var nexttrtd = nexttr.find("td:first");
    $.get(sLink, function(sData){
        nexttrtd.html(sData);
        nexttr.show();
    });
    $(this).click(function(){
        attachHideMyChildren();
    });
    return false;
}

function attachHideMyChildren()
{
    $(this).parent().parent().next("tr.version").hide();
    $(this).click(function(){
        attachShowMyChildren();
    });
}   

It opens the table row, inserts the data but then doesn't attach the function to close the row again. How can i get this to happen?

Any ideas?

回答1:

The problem is this:

$(this).click(function(){
  attachHideMyChildren();
});

When you call a function that way this becomes window. Instead do this:

$(this).click(attachHideMyChildren);

Also, you're adding click() handlers without removing the old ones.

That being said, there is an easier way of doing this.

$("a.version").click(function() {
  var next = $(this).closest("tr").next();
  if (next.is(":hidden")) {
    $.get($(this).attr("href"), function(sData) {
      next.find("td:first").html(sData);
      next.show();
    });
  } else {
    next.hide();
  }
  return false;
});

should about do it.