如何让jquery .closest()在这种特殊情况下工作?

时间:2013-06-25 22:55:42

标签: jquery html

好的,我一直在尝试使用jquery .closest()函数。我已经做了一些研究,但它必须是一些我无法弄清楚的逻辑,这让我疯狂。所以这里的代码请帮助。

<div class="tablecontainer">

mvcpartial with

<div class="emptycontainer"><p>no data in table</p></div>
<div class="populatedcontainer"><table><thead><tr></tr></thead>
    <tbody>
        <tr>
            <td><a onclick="deleteRow(this, @Model.ID)"></td>
        </tr>
    </tbody>
</table>
</div>

endpartial

</div>

deleteRow函数接受参数(that,id)。我可以删除该行,但是我遇到的问题是淡出div.populatedcontainer并在表为空时淡入div.emptycontainer。我试过了

var $table = $(that).closest('div.tablecontainer');
$('div.populatedcontainer', $table).fadeOut('slow');
$('div.emptycontainer', $table).fadeIn('slow');

我尝试测试选择器是否能够使用

找到div.tablecontainer
if ($table.length > 0) {
    console.log("located tablecontainer");
}

但是在调试期间没有显示在控制台中。如果重要的话,页面上有多组div.tablecontainer。

我试过var table; (没有$)。

我尝试了var $ that = $(那个);

我试过把它放在“if table is empty logic”之外,但它仍然不起作用

编辑:根据Felix Kling请求

tr有一个链接,点击时调用以下功能

onclick="deleteRow(this, @Model.ID)

并且该函数采用类似

的参数
function deleteRow(that, id){
   tried to do stuff like find the right div and fadeIn/fadeOut here (example attempts above)
}

感谢所有答案。特别是那些采用替代方法看起来很有希望我将不得不尝试明天哪些工作并更新这篇文章。

3 个答案:

答案 0 :(得分:1)

jsFiddle Demo

如果您的所有结构都相似,那么您可以使用prev。

var $table = $(that).parents('.populatedcontainer:first');
$table.fadeOut('slow').prev('.emptycontainer:first').fadeIn('slow');

答案 1 :(得分:0)

好吧,不使用最近父母

var $table = $(that).parents('div.tablecontainer').eq(0);
$table.find('div.populatedcontainer').fadeOut('slow');
$table.find('div.emptycontainer').fadeIn('slow');

答案 2 :(得分:0)

此方法不使用.closest(),但可以帮助您完成任务。假设您已将元素存储在名为“that”的变量中,您需要执行以下操作:

$(that).parent(".populatedContainer").siblings().fadeIn();
$(that).parent(".populatedContainer").fadeOut();