简体   繁体   中英

Why doesn't the following jquery script work?

I have a simple single page setup. Under a root folder, I have 3 subfolders (js, css, and images). In the root folder, I have an index.html page with the following content:

<html>
<head>
<title></title>
<script language="javascript" src="js/jquery-1.3.2.min.js"></script>
<script language="javascript" src="js/myscript.js"></script>
</head>
<body>
<a onclick="doSomething()" href="#" class="doSomething">Click!</a>
</body>
<html>

myscript.js contains the following code:

$('a.doSomething').click(function(){
//Do Something here!
alert('You did sometihng, woo hoo!');
});

When I click the link, nothing happens. What am I missing?

Wrap document.ready around the code:

$(document).ready(function() {
    $('a.doSomething').click(function(){
        //Do Something here!
        alert('You did sometihng, woo hoo!');
        return false; // return false to prevent default action
    });
});

As it is right now, you are trying to bind an event to an element that does not yet exist in the DOM.

Also, not sure why you have the onclick on the link itself, as the whole point of jQuery is to be able to take those ugly inline events out of there and bind them cleanly in the javascript. If you do this:

<a href="#" class="doSomething">yay click me</a>

And then use the code above, it should work fine.

At first I thought you were just missing a function named "doSomething". Then I realized you where expecting your selector to find the anchor tag anyway. However, that won't happen. At the time your script runs, the anchor hasn't been added to the DOM yet.

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