开发者

javascript if-else like php

Is it possible to do an if-else in JavaScript with HTML content like in PHP?

If so, how?

Example

<?php
if(1) {
开发者_StackOverflow?>

<h1>thought so</h1>

<?php
}
else {
?>

<h1>that's strange</h1>

<?php
}
?>


Here's a direct translation to javascript. Not normally the right approach though.

<script type="text/javascript">
if(1) {
      document.write('<h1>thought so</h1>');
}
else {
      document.write('<h1>that\'s strange</h1>');
}
</script>

Here's a better way:

<div id="show-if-true" style="display: none">
    <h1>thought so</h1>
</div>
<div id="show-if-false" style="display: none">
    <h1>that's strange</h1>
</div>

<script type="text/javascript">
var ifFalse = document.getElementById('show-if-false'),
    ifTrue  = document.getElementById('show-if-true');

if(1) {
    ifTrue.style.display = "block";
}
else {
    ifFalse.style.display = "block";
}
</script>


Not unless you are performing the if/else logic within javascript / jquery. HTML is wysiwyg.


I think you want to do:

if(something){
      //do something
      document.write('<h1>thought so</h1>'); //see comments below
}
else if(something_else) {
      //do something else
      document.write('<h1>that\'s strange</h1>'); //see comments below
}

Fiddle: http://jsfiddle.net/maniator/mQytV/


No, you cannot embed html in javascript. What php does it "print" the html as you go along on the server, javascript can't do that - it can't actually generate html. That's what the DOM interface is for.


Sorry I misread you. This is very possible in javascript, but might I suggest using jQuery instead? jQuery is a very powerful, widely used javascript framework.

In jQuery you can call and DOM element and set the HTML inside it with a simple .html("asdasda") like syntax! And ofcourse you have if - else, foreach, switch, etc.

This is very possible, however the degree of conditions you can validate is limited since you cannot define variables, etc in HTML (before HTML 5).

You can refer this link http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx

Basically they syntax is HTML CONTENT

Where HTML content will be hidden on true conditional outcome.

Let me know if you have any particular code in mind to do this for.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜