高!
我想做的是:我有一个表,其中的 onclick 附加到驻留在偶数行表中的链接。每个奇数行都被隐藏。单击该链接时,会显示奇数行并将数据加载到该行中。工作正常
现在我想做的是,每当该过程完成时,我想将一个新的单击功能附加到该链接,使该行再次隐藏。有点像切换,但还有一些不仅仅是显示/隐藏功能。我尝试使用以下代码来做到这一点,但无法让它工作。
我肯定错过了一些非常基本的东西,或者只是不太了解jquery(这很有可能,因为我几周前才刚刚开始)。
$(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();
});
}
它打开表行,插入数据,但然后不附加函数来再次关闭该行。我怎样才能让这种情况发生?
有什么想法吗?
最佳答案
问题是这样的:
$(this).click(function(){
attachHideMyChildren();
});
当你调用一个函数时,this
就变成了window
。相反,这样做:
$(this).click(attachHideMyChildren);
此外,您还添加了 click()
处理程序,而不删除旧的处理程序。
话虽这么说,有一种更简单的方法可以做到这一点。
$("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;
});
应该这样做。
关于jquery 将 $(this) 传递给其他函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2036647/