简体   繁体   English

使javascript如果语句显示html?

[英]Make javascript if statement display html?

I wanted an if statement to show an image or html code depending on the webpage. 我想要一个if语句来显示图像或html代码,具体取决于网页。 I got this far and the html table doesn't appear at all (appears blank): 我到这为止,并且html表根本没有出现(显示为空白):

<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 我已经假设您拥有JQuery因为它已被标记

You're using document.innerHTML , which doesn't exist . 您正在使用不存在的 document.innerHTML 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. 抛开这种方法的所有其他问题,我不确定,为什么要在一个分支中使用document.write()在另一个分支中使用someElement.innerHTML

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: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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