开发者

jQuery can't apply onmousedown to anchor tags

开发者 https://www.devze.com 2023-03-25 09:09 出处:网络
I have a navigation menu like this <ul id=\"nav\"> <li> <a id=\"firstLink\" href=\"#\"> Link 1 </a> </li>

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());
});
0

精彩评论

暂无评论...
验证码 换一张
取 消