开发者

How to display a certain portion of a site depending on a javascript variable?

Suppose I have a javascript variable "is_valid"

If the variable is 1, I'd like to display:

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

Otherwise...

<div>NOT valid</div>...and a big chunk of other code开发者_开发知识库

I do NOT want to use INNERHTML. I want to do it like this:

<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>


Put the code in an element that you can show or hide. Example:

<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>


Suppose you have:

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

Then, in your JavaScript:

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

Or, if you use jQuery:

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


Supposing that you already have the content on the page and just want to toggle visibility, you can do the following.

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" : "";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜