如何根据javascript变量显示网站的某个部分?

时间:2009-10-23 21:37:36

标签: javascript

假设我有一个javascript变量“is_valid”

如果变量为1,我想显示:

<div>It's valid!</div> ...and a big chunk of other code

...否则

<div>NOT valid</div>...and a big chunk of other code

我不想使用INNERHTML。我想这样做:

<script type="text/javascript">
    if(is_valid == 1){
</script>
    It's valid!
<script type="text/javascript">
    }else{
</script>
    It's not valid
<script type="text/javascript">
    }
</script>

3 个答案:

答案 0 :(得分:3)

将代码放在可以显示或隐藏的元素中。例如:

<div id="Valid">
  <div>It's valid!</div> ...and a big chunk of other code
</div>
<div id="Invalid">
   <div>NOT valid</div>...and a big chunk of other code
</div>

<script type="text/javascript">
document.getElementById('Valid').style.display = (is_valid == 1 ? 'block' : 'none');
document.getElementById('Invalid').style.display = (is_valid == 1 ? 'none' : 'block');
</script>

答案 1 :(得分:2)

假设你有:

<div id="isvalid">It's valid!</div>
<div id="isnotvalid">NOT valid!</div>
... blah blah ...

然后,在您的JavaScript中:

document.getElementById("isvalid").style.display = is_valid ? "" : "none";
document.getElementById("isnotvalid").style.display = is_valid ? "none" : "";

或者,如果你使用jQuery:

$("#isvalid").toggle(isvalid);
$("#isnotvalid").toggle(!isvalid);

答案 2 :(得分:1)

假设您已在页面上拥有内容并且只想切换可见性,则可以执行以下操作。

<强> HTML

<div id="valid_section">....</div>
<div id="invalid_section">....</div>

<强>的JavaScript

document.getElementById("valid_section").style.display   = is_valid ? ""     : "none";
document.getElementById("invalid_section").style.display = is_valid ? "none" : "";