简体   繁体   中英

Make javascript if statement display html?

I wanted an if statement to show an image or html code depending on the webpage. I got this far and the html table doesn't appear at all (appears blank):

<script type="text/javascript">
<!--
var url = document.location.pathname;

if( document.location.pathname == '/tagged/photos' ){
document.innerHTML('<table><tr> hello </tr> </table>');
}

if( document.location.pathname == '/tagged/news' ){
document.write("<b>This is my news page</b>");
}
//-->
</script>

I'd do it slightly differently

Add both markup to the page, and show/hide as approproate:

<table id="table"><tr> hello </tr></table>
<span id="title"><b>This is my news page</b></span>

<script type="text/javascript">
$(function(){
    var url = document.location.pathname;
    if( url == '/tagged/photos' ){
        $('#title').hide();
        $('#table').show();
    }
    if( url == '/tagged/news' )
    {
        $('#title').show();
        $('#table').hide();
    }
})
</script>

I have assumed you have JQuery since it is tagged

You're using document.innerHTML , which doesn't exist . At the very least, you need to get a proper element:

document.documentElement.innerHTML = 'some HTML';

Setting aside everything else that's wrong with this approach, I'm not sure, why would you use document.write() in one branch and someElement.innerHTML in the other.

I'd suggest the following approach:

 function pagePopulate() { // you're looking at the pathname, use a sensible (meaningful) variable-name: var pagePath = document.location.pathname, // this is a map, of the relationship between page and content: pathToContent = { // pagename : html 'photos': '<table><tbody><tr><td>photos page</td></tr></tbody></table>', 'news': '<b>This is the news page</b>' }, // getting a reference to the <body> element: body = document.querySelector('body'); // setting the innerHTML of the <body>, // if pagePath = 'tagged/photos', splitting with '/' would return: // ['tagged','photos'], calling 'pop()' returns the last element of the array // 'photos', which returns that string to the square brackets, resulting in: // pathToContent['photos'], which would yield the '<table>...</table>' HTML. // if that call resulted in an undefined, or falsey, value, then the default // (the string *after* the '||' would be used instead: body.innerHTML = pathToContent[pagePath.split('/').pop()] || '<h2>Something went wrong</h2><img src="http://blog.stackoverflow.com/wp-content/uploads/error-lolcat-problemz.jpg" />'; } // calling the function: pagePopulate(); 

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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