2014-11-23 1 views
0

Мне нужен оператор if, чтобы показать изображение или код html в зависимости от веб-страницы. Я получил это далеко, и HTML таблицы не отображается на всех (кажется пустым):Сделать javascript, если оператор display 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

Разве это не работает? –

+1

И вопрос? :) – hawk

+0

Кроме того, я не вижу никаких jquery здесь :) –

ответ

0

Я хотел бы сделать это немного по-другому

Добавить как разметку страницы, и показать/скрыть, как 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> 

я предположил, что у вас есть JQuery, так как он помечен

0

вы используете document.innerHTML, который doesn't exist. По крайней мере, вы должны получить правильный элемент:

document.documentElement.innerHTML = 'some HTML'; 

Откладывая все остальное, что не так с этим подходом, я не уверен, почему вы бы использовать document.write() в одной отрасли и someElement.innerHTML в другой.

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

Ссылки:

Смежные вопросы