简体   繁体   中英

unable to attach an event in javascript

i am brand new to javascript.. i am reading a book called DOM SCRIPTING..

I tried to code an example but unfortunately the link shows direct image.. What i am trying to do is to swap images. here is the js code

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

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

        }

    }

And here is my html Code

   <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

Please tell me where i am doing wrong.. Thanks...

You don't need this:

document.ready = function () {

}

just define the function. Since you have the function inside another, it is only in local scope and not in global scope where the onclick handler is looking. Better though, would be giving the element an id:

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

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

attachEvent documentation

addEventListener documentation


You are probably confusing jQuery's $(document).ready(function(){}); with normal DOM. That is a shortcut for

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

which will fall back to the window onload event in older browsers. If you want to wrap everything up in a single function, you want:

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;
    }
}

so that your function is defined in the same scope that you're assigning to the element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM