简体   繁体   English

如何将元素设置为默认条件(隐藏())以及单击时的设置(显示())

[英]How to set an element to a default condition (hide ()) and when clicked (show())

Say I have a left-side chat bar with chat users. 说我有一个聊天用户的左侧聊天栏。 Each user has their image (much like Facebook's chat)and is clickable to open a chat box to start chatting away. 每个用户都有自己的图像(很像Facebook的聊天),可以单击以打开聊天框以开始聊天。

Here's my code: 这是我的代码:

$('.msg_wrap').hide();
$('.msg_box').hide();
    $('.chat_user').click(function() {          
        $('.msg_wrap').show();
        $('.msg_box').show();
} 

I know this is wrong but what I want to do here is when the page loads for the first time, all the chatboxes to be hidden (hide ()). 我知道这是错误的,但是我要在这里做的是,当页面首次加载时,所有聊天框都将被隐藏(hide())。 It is not until I click on a chat user (.chat_user) that a pop up/chat box appears (show()). 直到我单击聊天用户(.chat_user)时,才会出现一个弹出/聊天框(show())。 How do I fix this code? 如何修复此代码? Do I have to create a function? 我必须创建一个功能吗?

A quick thought on a solution. 快速思考解决方案。

First. 第一。 Set the elements ('.msg_wrap') and ('.msg_box') to hidden in your html and kill your first two lines of code. 将元素('.msg_wrap')和('.msg_box')设置为隐藏在html中,并杀死前两行代码。 I am not sure what those elements specifically are, but, for example, if they were div tags it would look something like: 我不确定这些元素具体是什么,但是例如,如果它们是div标签,它将看起来像:

<div hidden class="msg_wrap">

Second. 第二。 I am not sure if you are saying that the code currently isn't working on page load. 我不确定您是否在说当前代码无法在页面加载中使用。 It looks like you are missing a ) at the end and also you can update to the following so that it gets executed on page load. 看起来您最后缺少),并且您也可以更新以下内容,以便在页面加载时执行它。

$(function(){
   $('.chat_user').click(function() {          
        $('.msg_wrap').show();
        $('.msg_box').show();
    }); 
});

This is jquery shorthand for $( document ).ready(). 这是$(document).ready()的简写形式。

Also, if you want the msg_wrap and msg_box elements to toggle between being hidden and shown you can use the toggle() method instead of show(). 另外,如果希望msg_wrap和msg_box元素在隐藏和显示之间切换,则可以使用toggle()方法代替show()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM