开发者

semantically correct jQuery trigger

开发者 https://www.devze.com 2023-02-05 12:28 出处:网络
When developing with jQuery, i often turn to using href=\'#\' id=\'myTrigger\' as a trigger for an event, in which i combine with return false to stop it actually being used as a hyperlink. Whenever i

When developing with jQuery, i often turn to using href='#' id='myTrigger' as a trigger for an event, in which i combine with return false to stop it actually being used as a hyperlink. Whenever i have posted code up here before, i have been lynched by some of the more experienced people for using a hyperlink as a trigger. Should i be using input type="button", or just give any element a开发者_开发百科n ID and use that as the trigger?

What the best practice for jQuery triggers?


That depends on what you are doing, and what the default behavior of the element is.

If you are for example replacing the default behaviour of a link by opening the page in a popup, it makes perfect sense to use a link. Search engines will still see the link, and it will degrade gracefully for those few who have disabled client script.

If you on the other hand is using an event for something that is completely different from the navigation that you would use a link for, you should rather use a different element.

To stop the default behaviour of a link, you can use the preventDefault method. Example:

$('a#info').click(function(e){
  alert('info');
  e.preventDefault();
});

Note that there is no requirement to use an id to target the element where you want to catch the event. An id is an efficient way to target elements, but any method of targetting the element is valid. Example:

<div class="button">Eat me</div>

$('.button').click(function(){ alert('Eaten.'); });


I usually do something like:

<div id=myTrigger'>Click Me</div>

with:

$('#myTrigger').click( function() { /* do stuff */ })

... you don't then need the return false to stop the href firing, which I've had problems with in the past; if you click it before the JavaScript has run, it'll fire anyway, for instance. This way also seems sort of 'right' to me, but there are other ways to do it.

You can of course, use pretty much anything for the thing to click; div, span, img, button, etc. - I hardly ever use submit anymore, always a button used as above. Just use what's best at the time...


You should use whatever is appropriate in the situation. Don't add a hyperlink, just add a click event to whatever element is already there. if it's a <p> then add the click event to the <p> if it's an <img> then add it to that.

0

精彩评论

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

关注公众号