javascript - 将类添加到具有特定子项的父项

标签 javascript jquery

当我点击 .input 类时,我想将类 .hidden 添加到父级,而 .input 的父级类有一个 child .delete。否则,移除父对象而不是仅仅隐藏它。问题是它总是将 .hidden 类添加到父级,无论如何。

HTML:

<div class='container'>
    <input class='input' type='text'>
    <input class='input delete' type='text'>
</div>
<div class='container'>
    <input class='input' type='text'>
</div>

JS:

$('.input').on('click', function() {

    var element = $(this);

    if (element.parent().has('.delete')) {
            element.parent().addClass('hidden');
        } else {
            element.parent().remove();
    }
});

最佳答案

在你的具体情况下

   element.parent().has('.delete')

返回一个 jQuery 对象,其中包含一个或零个 DOM 元素。在“if”语句中使用,这将评估为 true,因此您永远不会得到 else 情况。

改为使用

   element.parent().has('.delete').length

这将返回 0 或 1。零将在 if 语句中评估为 false。

关于javascript - 将类添加到具有特定子项的父项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32258380/

相关文章:

php - SVN 存储库新手问题

javascript - 从 JQuery UI 对话框提交 MVC 部分页面

php - 为什么 jQuery 在我的网站上不起作用?

javascript - jquery-ui 工具提示功能中的选项对工具提示没有任何影响

Javascript 快照.svg : Rotation animation goes the long way around at 270 degrees

javascript - Jquery数据表页码问题

jquery 检测输入文件类型返回空

javascript - 如何在 jQuery 中存储 key

javascript - 悬停时使 DIV 显示在光标旁边

javascript - 无法通过 JavaScript 单击隐藏按钮