[英]How to display a list of data from Javascript into a Select Statement 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.