繁体   English   中英

使javascript如果语句显示html?

[英]Make javascript if statement display html?

我想要一个if语句来显示图像或html代码,具体取决于网页。 我到这为止,并且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>

我会略有不同

将两个标记都添加到页面,并以适当的方式显示/隐藏:

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

我已经假设您拥有JQuery因为它已被标记

您正在使用不存在的 document.innerHTML 至少,您需要获取适当的元素:

document.documentElement.innerHTML = 'some HTML';

抛开这种方法的所有其他问题,我不确定,为什么要在一个分支中使用document.write()在另一个分支中使用someElement.innerHTML

我建议采用以下方法:

 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(); 

参考文献:

暂无
暂无

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

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