2016-01-20 33 views
3

調用從HTML一個javascript我有以下的頁腳的HTML代碼如何使用ID

<footer class="footer"> 
     <div class="container"> 
      <p class="text-muted"> <a href="about.html">About Us</a> | <a href="contactus.html">Contact Us</a></p> 
      <p class="text-muted">&copy; Copyright of abc 
       <span id="yearfooter"> </span> 
      </p> 
     </div> 
</footer> 
<script src="scripts/abc.js"></script> 

和我的JScript以下

$(function() { 
$('#yearfooter').footer({ 
    document.write(new Date().getFullYear()); 
}); 

});

我很新的javascript。我試圖讓這個腳本動態獲取當前年份並在頁腳中顯示。但是,憑藉這一點,我似乎根本看不到年份。我不確定我在這裏做錯了什麼。

+10

'$( '#yearfooter')標記這個問題與jQuery文本((新的Date())。 getFullYear())' – adeneo

+1

@Michelle你的jQuery語法不正確,使用'document.write()'可能會影響性能。 – Raptor

+0

由於您在dom準備好之後調用'document.write()',它會替換文檔中的所有內容 –

回答

1

使用document.write將覆蓋的網頁,所以你想是這樣的:

$(function() { 
 
    $('#yearfooter').text(new Date().getFullYear()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<footer class="footer"> 
 
     <div class="container"> 
 
      <p class="text-muted"> <a href="about.html">About Us</a> | <a href="contactus.html">Contact Us</a></p> 
 
      <p class="text-muted">&copy; Copyright of abc 
 
       <span id="yearfooter"> </span> 
 
      </p> 
 
     </div> 
 
</footer>

1

$('#yearfooter')創建一個包裝ID爲「yearfooter」的元素的jQuery對象。由於它是一個jQuery對象,因此您只能調用jQuery方法(或由jQuery插件添加的方法)。 footer不是jQuery方法。

由於您只是想更新「yearfooter」範圍內的文本,因此您可能需要jQuery text method。該語法也只是:

$('#yearfooter').text(new Date().getFullYear()); 
1

您可以簡單地使用這個片段獲得結果

function() { 
    var date = new Date(); // Get the date object 
    var year = date.getFullYear(); // get year from date object 
     // use textcontent to put the text inside the relevant tag using its id 
    document.getElementById("yearfooter").textContent = year 
    }; 

否TE:既然你已經不那麼僅使用JavaScript的

WORKING EXAMPLE

+0

請注意,IE8不支持textContent。但是,MS剛剛放棄了對IE8的支持,所以希望你的網站不再需要它支持它(但是我知道這對每個人都是不正確的)。假設你不需要支持它,這可能是最好的解決方案,除非你要用jQuery對象做其他事情。當document.getElementById在這種情況下工作時,爲什麼要創建jQuery對象的性能? – Elezar

1

$(document).ready(function(){ 
 
    $('#yearfooter').html(new Date().getFullYear()); 
 
});
<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script> 
 
<footer class="footer"> 
 
     <div class="container"> 
 
      <p class="text-muted"> <a href="about.html">About Us</a> | <a href="contactus.html">Contact Us</a></p> 
 
      <p class="text-muted">&copy; Copyright of abc 
 
       <span id="yearfooter"> </span> 
 
      </p> 
 
     </div> 
 
    </footer>