can i separate JavaScript If condition?
in PHP we can put HTML between codes like this:
<?php
if (condition) {
?>
<p>True</p>
<?php
} else {
?>
<p>True</p>
<?php
}
?>
can we do this in javascript ? like this ?
<script language='JavaScript'>
if (condition) {
</script>
<p>True</p>
<script langu开发者_如何学Goage='JavaScript'>
} else {
</script>
<p>True</p>
<script language='JavaScript'>
}
</script>
There's something like this that has the effect you posted (maybe not your intention though, it's hard to say), but I wouldn't do it.
<script type="text/javascript"> //language == deprecated!
if (condition) {
document.write('<p>True<\/p>');
} else {
document.write('<p>True<\/p>'); //maybe False here?
}
</script>
But again this is just a demonstration of the effect, try to avoid document.write
(it' a blocking operation) whenever possible.
Update: Edited based on comments below to make this example you shouldn't use! valid, but you shouldn't be copy/pasting it in the first place...
No. Browsers will output things in order that it sees them, without considering any conditions of other media on the page.
This works in PHP because the PHP interpreter interprets your code before sending the output to the client browser window. In other words, the actual HTML document being sent to the client is parsed and computed before being sent to the requesting browser. With Javascript mostly being a client-side scripting language this method is not possible, since you already have your HTML document generated from a server-side language such as PHP. You can manipulate the document in other ways using Javascript, with technologies such as Ajax and the DOM.
not that i know of, but for php do this instead
<?php if (condition): ?>
<p>True</p>
<?php else: ?>
<p>False</p>
<?php endif; ?>
=)
精彩评论