JQuery event for the first named element only

I have hyperlinks, all of them are called "mylink". They should fire the same event, but only the first element with the name "mylink" actually fires. My code is as follows:

 $(document).ready(function() { 
        $("#formID").validationEngine() 
        $('#mylink').click(function(e){ 
           var goto = $(this).attr('href'); //get the url 
           $.ajax({ 
              url: goto 
           }); //execute the href 
           e.preventDefault(); //prevent click
           $('#mylink').parent().parent().fadeOut("slow");
        }); 
    })

Where am I going wrong?

+3
source share
4 answers
$(function(){
  $("#formID").validationEngine(); // don't forget your semi-colons
  $(".mylink").click(function(e){  // ID should be unique, use classes instead
    e.preventDefault();
    $.ajax({ url: $(this).attr("href") });
    $(this).parent().parent().fadeOut("slow"); // refer to this as 'this'
  });
});
+5
source

You cannot reuse the id value. This "id" can be used only once per page.

If you need several elements that need to be affected, use the "class" component:

<div id="uniqueString" class="makeMeMoo makeMePurple makeMeClickable">
  <!-- whatever -->
</div>
+7
source

.

.

+2

, , , , (# mylink), jquery .

 $('a.mylink').click(function(e) { 
+1
source

Source: https://habr.com/ru/post/1731286/


All Articles