jquery passing $(this) to other functions

随声附和 提交于 2019-12-02 04:50:57

问题


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.



来源:https://stackoverflow.com/questions/2036647/jquery-passing-this-to-other-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!