功能切换 - 打开所有项目

function toggle - open all items

伙计们

我有以下 HTML 带换行(注意换行)的代码:

<div class="notice-title">
    Title
</div>

<div class="notice-content">
    Content text
</div>

<div class="notice-toggle" value="Hide" onclick="toggle()">
    <a href="#"><img src="../img/icon_rollout.png"></a>
</div>

和切换脚本

    function toggle() {
    var newStatus = $('.notice-toggle').val() === "Hide" ? "Show" : "Hide";
    $('.notice-toggle').val(newStatus);
    if (newStatus == "Show") {
        $("div.notice-content").css('overflow','hidden');
        $("div.notice-content").css('height','80px');
        $("div.notice-wrap").css('height','187px');
    }
    else {
        $("div.notice-content").css('overflow','visible');
        $("div.notice-content").css('height','100%');
        $("div.notice-wrap").css('height','100%');
    }
}

当我点击开关时,打开一次所有项目。如何让开场只有我选择的那个元素?

P.S。我也用 Angular

提前致谢!

也许你可以改变这个:

function toggle() {
    var newStatus = $('.notice-toggle').val() === "Hide" ? "Show" : "Hide";
    $('.notice-toggle').val(newStatus);
    if (newStatus == "Show") {
        $("div.notice-content").css('overflow','hidden');
        $("div.notice-content").css('height','80px');
        $("div.notice-wrap").css('height','187px');
    }
    else {
        $("div.notice-content").css('overflow','visible');
        $("div.notice-content").css('height','100%');
        $("div.notice-wrap").css('height','100%');
    }
}

至:

function toggle() {
    var noticeToggleElement = $(this);
    var newStatus = noticeToggleElement.val() === "Hide" ? "Show" : "Hide";
    noticeToggleElement.val(newStatus);
    if (newStatus == "Show") {
        noticeToggleElement.css('overflow','hidden');
        noticeToggleElement.css('height','80px');
        $("div.notice-wrap").css('height','187px');
    }
    else {
        noticeToggleElement.css('overflow','visible');
        noticeToggleElement.css('height','100%');
        $("div.notice-wrap").css('height','100%');
    }
}

因为您应该拥有通过单击鼠标打开的元素的上下文。

当您使用 jQuery 时,如果您从 HTML 标记中删除 onclick 并在您的 javascript 代码中对一个函数进行绑定,应该会更好在文件就绪时执行:

$(function(){

    $('div.notice-content').click(toggle);

})

但这只是加分项。

您首先应该做的是将该样式从 js 移动到 css, 并有您的 类 的其他变体,例如:

.notice-title--toggled {
...
}

.notice-content--toggled {
...
}

.notice-toggle--toggled {
...
}

现在你已经很好地分离了关注点,你的切换函数可以只切换 类 这些元素。 您还应该将此切换点击处理程序放在文档准备就绪上,因此最终结果将是:

$(function) {
  $('.notice-toggle').click(function() {
    $('.notice-title').toggleClass('notice-title--toggled');
    $('.notice-content').toggleClass('notice-content--toggled');
    $('.notice-toggle').toggleClass('notice-toggle--toggled');
  });
}