I have a navigation menu like this
<ul id="nav">
<li> <a id="firstLink" href="#"> Link 1 </a> </li>
<li>开发者_如何学JAVA <a id="secondLink" href="#"> Link 2 </a> </li>
<li> <a id="thirdLink" href="#"> Link 3 </a> </li>
<li> <a id="fourthLink" href="#"> Link 4 </a> </li>
</ul>
I'd like to associate a function to each anchor tag as the mouse is down so I have an external js file and my code is
$(document).ready(function() {
$('#firstLink').onmousedown(doSomething());
[ ... ]
});
function doSomething() {
// this function does something
}
My problem is if I put the event handler inline, the script works and no issue is brought up.
<li> <a href="#" id="firstLink" onmousedown="doSomething()"> Link 1 </a> </li>
On the other hand if I use the external file, as shown above, nothing happens and Chrome gives me back Uncaught TypeError: Object [object Object] has no method onmousedown
, Firefox and Firebug return me $("#firstLink").onmousedown is not a function
. I don't understand, what am I doing wrong?
$('#firstLink').onmousedown(doSomething());
should be
$('#firstLink').mousedown(doSomething);
It is mousedown and not onmousedown.
$(document).ready(function() {
$('#firstLink').mousedown(doSomething());
[ ... ]
});
you can prevent the default event by doing something like this:
$('#firstLink').onmousedown(function(e){
e.preventDefault();
// do something
});
Documentation here
But you might want to condier using ´.click()´ instead of mousedown.
You could also use the "on" event handler. As of Jquery 1.7, this is the proper way to attach an Event - it replaces bind(), delegate() and live().
$(document).ready(function() {
$('#firstLink').on("mousedown", doSomething());
});
精彩评论