2013-02-24 40 views
0

我是全新的JavaScript事件.. 我讀了一本書叫DOM腳本..無法附加在JavaScript

我試圖代碼的例子可惜鏈接顯示直接圖像.. 什麼我試圖做的是交換圖像。 這裏是js代碼

document.ready = function() { 
    function showPicture(pictureChoosen) { 
      var source = pictureChoosen.getAttribute('href'); 

      var placeholder = document.getElementById('plaecehlder'); 
      placeholder.setAttribute('src', source); 

     } 

    } 

這裏是我的HTML代碼

<ul> 
    <li><a href="images/journee.jpg" onclick="showPicture(this);return false;">Journee</a></li> 
    <li><a href="images/coffee.jpg">Coffee</a></li> 

</ul> 
<img id="plaecehlder" src="*" alt="" />Placeholder 

請告訴我,我做錯了..謝謝...

+1

'document.ready = fn'聽起來更像僞碼而不是香草JS。 – 2013-02-24 15:39:29

+0

您的頂級功能只定義一個功能。它不執行......只定義。 – 2013-02-24 15:46:33

+0

嘗試不使用document.ready! – 2013-02-24 15:48:31

回答

1

你不需要這個:

document.ready = function() { 

} 

只是定義函數。由於您在另一個函數中有函數,因此它只在本地範圍內,而不在全局範圍內,其中onclick處理函數正在查找。雖然較好,將給出元素的ID:

document.getElementById("foo").attachEvent // IE 

document.getElementById("foo").addEventListener // standards-compliant 

attachEvent文檔

addEventListener文檔


你可能混淆jQuery的$(document).ready(function(){});正常的DOM。這是

document.addEventListener("DOMContentLoaded", function(){}, false); 

一個快捷方式,這將回落到窗口onload事件在舊的瀏覽器。如果你想在一個單一的功能包了一切,你想:

window.onload = function() { 

    function showPicture(pictureChoosen) { 
     var source = pictureChoosen.getAttribute('href'); 
     var placeholder = document.getElementById('plaecehlder'); 
     placeholder.setAttribute('src', source); 

    } 

    document.getElementById("foo").onclick = function() { 
     showPicture(this); 
     return false; 
    } 
} 

讓你的功能是在你指定的元素相同的範圍界定。

+0

是的謝謝,它的工作,但我想要的功能ony完全加載Dom後。我的意思是封閉在window.onload函數內,然後它不會運行?你能告訴我爲什麼嗎?? – designerNProgrammer 2013-02-24 15:53:22

+0

感謝Info Pal。 – designerNProgrammer 2013-02-24 16:02:50