Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Javascript显示和隐藏消息_Javascript_Jquery_Html_Css - Fatal编程技术网

使用Javascript显示和隐藏消息

使用Javascript显示和隐藏消息,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我已经设置了一个小脚本来显示和隐藏div $('.message-head').click(function () { $('.message-preview').toggle('slow'); }); 它本该如此完美地工作。我的问题是页面上有多个html标记实例,它位于foreach循环中 <div class="two-three-col message-head"> <h4>@message.Subject</h4> <d

我已经设置了一个小脚本来显示和隐藏div

$('.message-head').click(function () {
    $('.message-preview').toggle('slow');
});
它本该如此完美地工作。我的问题是页面上有多个html标记实例,它位于foreach循环中

<div class="two-three-col message-head">
    <h4>@message.Subject</h4>
    <div class="message-preview">
        @Html.Raw(@message.Body)
    </div>
</div>

@信息。主题
@Html.Raw(@message.Body)
这是一个基本的消息系统,已经被切碎和改变了很多,已经留给我来修复;我不是javascript的高手,我被卡住了。那么,我如何修改js,以便如果我点击消息1,那么只有消息1会在点击时显示/隐藏,其余的将保持不活动状态


提前感谢

您可以使用
this
关键字来引用引发事件的元素。从那里,您可以遍历DOM以查找相关的
.messagepreview
元素。试试这个:

$('.message-head').click(function () {
    $(this).find('.message-preview').toggle('slow');
});

值得一提的是,如果将动态创建
.messagehead
元素,那么最好使用
文档
绑定事件。效果非常好@Rory谢谢。干得好,我很快就要上一门Javascript课程了,因为看起来我会对新版本有更多的了解system@Damien没问题,很乐意帮忙