我希望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>
答案 0 :(得分:0)
&#39; d略有不同
将两个标记添加到页面,并根据需要显示/隐藏:
<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
,因为它被标记为
答案 1 :(得分:0)
您正在使用document.innerHTML
doesn't exist。至少,你需要得到一个合适的元素:
document.documentElement.innerHTML = 'some HTML';
撇开这种方法的其他一切错误,我不确定,为什么你会在一个分支中使用document.write()
而在另一个分支中使用someElement.innerHTML
。
答案 2 :(得分:0)
我建议采用以下方法:
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();
&#13;
参考文献: