Handling jquery events for links

I get started with jquery and follow the tutorial on the official site found here. http://docs.jquery.com/How_jQuery_Works#jQuery:_The_Basics

I'm in the section "Running the code in the document is ready." If you notice, they give two examples. One where the warning window appears before you get to the jquery site, and the other where the warning window prevents you from going to the site.

Suppose I have two links. Where a warning window appears, and after clicking "OK" it goes to the jquery site, and another - a warning window appears, but does not allow you to go to the jquery site. I just wanted to know different answers for different links. Do I need to specify some kind of identifier?

Here is the code.

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
<title>Demo</title>
  </head>
  <body>
<script src="jquery.js"></script><br/>
<a href="http://jquery.com/" id="1">jQuery</a><br/> <!--first link: will display message and then proceed to site -->
<script>
 $(document).ready(function(){
    $("a#1").click(function(event){
      alert("Thanks for visiting!");
    });
  });
</script>
<a href="http://jquery.com/" id="2">jQuery</a> <!-- second link: message appears and does not continue to site -->
<script>
   $(document).ready(function(){
      $("a#2").click(function(event){
        alert("As you can see, the link no longer took you to jquery.com"); 
        event.preventDefault();
      });
    });
</script>

  

edit - . , , .

+3
4

, id - .

<a id="anchor1" href="..">anchor 1</a>

$("#anchor1").click(function(event){
   alert("Thanks for visiting!");
   event.preventDefault();
});
+5

, $('a') ('a'-tags). , , , . , , id, :

<a id="anchor1" href="..">anchor 1</a>

$('#anchor1').click(...);

, a-, ref data- *, :

<a rel="preventme" href="..">anchor 1</a>

$('a[rel="preventme"]').click(...);

<a data-mode="disable-link" href="..">anchor 2</a>

$('a[data-mode="disable-link"]').click(...)

,

$("a[href^='http://']").click(...);
+5

.

$('a') , <a> . , , - , . , - , , . , , / .

, @Sam Tyson, jQuery:

 $('#id1').click(

jQuery id1 #, jQuery, - ID.

- . , , , , , , , . , , , , . :

$('.do_not_follow_link').click(function (e) {
    e.preventDefault();
});

do_not_follow_link , .

, jQuery, , , .

+3

You really need to assign an identifier to links and refer to that identifier when linking your events. See jsFiddle for a working example.

<a href="http://jquery.com/" id="link1">jQuery</a><br/> <!--first link: will display message and then proceed to site -->
<a href="http://jquery.com/" id="link2">jQuery</a> <!-- second link: message appears and does not continue to site -->

Then bind events:

$(document).ready(function() {
    $("#link1").click(function(event) {
        alert("As you can see, the link no longer took you to jquery.com");
        event.preventDefault();
    });

    $("#link2").click(function(event) {
        alert("Thanks for visiting!");
    });
});​
+1
source

All Articles