简体   繁体   English

使用if语句使用javascript隐藏div

[英]hide a div using javascript using if statement

I want to hide a div with id apDiv1 using javascript when the values are not equal, I am using the following code.But it is not working. 我想隐藏一个id为apDiv1的div,当值不相等时使用javascript,我使用下面的代码。但它不起作用。

<script>
/* <![CDATA[ */
if (#{sessionScope['userdet']['email']}!=#{sessionScope['frienddet']['email']}){
$('#apDiv1').hide();
}
/* ]]> */
</script>

The rendered code is as follows: 呈现的代码如下:

<script>
    /* <![CDATA[ */
    if (amlan@ymail.com != atinr4@gmail.com){
     $('#apDiv1').hide();
    }
    /* ]]> */
</script>

The rendered code is not valid JS - you've got a syntax error on the if condition because you need to quote the strings that contain the email addresses. 渲染的代码无效JS - 您在if条件上遇到语法错误,因为您需要引用包含电子邮件地址的字符串。 That is, your rendered code should look like this: 也就是说,您呈现的代码应如下所示:

if ("amlan@ymail.com" != "atinr4@gmail.com"){

Or you can use single quotes, JS allows either (as long as they match for any particular string literal). 或者你可以使用单引号,JS允许(只要它们匹配任何特定的字符串文字)。

I don't know what your source language is, but I assume you could get the rendered result that you need with something like this: 我不知道你的源语言是什么,但我认为你可以用这样的东西得到你需要的渲染结果:

if ("#{sessionScope['userdet']['email']}"!="#{sessionScope['frienddet']['email']}"){

EDIT: Have you included the jquery.js file on your page? 编辑:您是否在页面上包含了jquery.js文件? You didn't use the jquery tag on your question, but the $("#apDiv1").hide() part uses jQuery functions $() and .hide() . 您没有在问题上使用jquery标记,但$("#apDiv1").hide()部分使用jQuery函数$().hide() If you don't have jQuery try something like this: 如果你没有jQuery尝试这样的事情:

document.getElementById("apDiv1").style.display = "none";

Also, the code you've shown will only be able to find the div if the script block appears after it, or if you wrap your code in a document ready handler as follows (though this also assumes jQuery is available): 此外,您显示的代码只能在脚本块出现后才能找到div,或者如果您将代码包装在文档就绪处理程序中,如下所示(尽管这也假设jQuery可用):

$(document).ready(function() {

    // your other code here    
});

Non-jQuery version using an onload handler: 使用onload处理程序的非jQuery版本:

window.onload = function() {

    // your other code here
};

您需要将2(电子邮件)值括在引号中

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

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