jQuery事件仅针对第一个命名元素触发

Geo*_*ton 3 jquery events

我有超链接,都被命名为'mylink'.它们都应该触发相同的事件,但只有名为'mylink'的第一个元素才会触发.我的代码如下:

 $(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");
        }); 
    })
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

Poi*_*nty 7

您无法重复使用"id"值.给定的"id"只能在页面上使用一次.

如果需要影响多个元素,请使用"class"组件:

<div id="uniqueString" class="makeMeMoo makeMePurple makeMeClickable">
  <!-- whatever -->
</div>
Run Code Online (Sandbox Code Playgroud)


Sam*_*son 5

$(function(){
  $("#formID").validationEngine(); // don't forget your semi-colons
  $(".mylink").click(function(e){  // ID's should be unique, use classes instead
    e.preventDefault();
    $.ajax({ url: $(this).attr("href") });
    $(this).parent().parent().fadeOut("slow"); // refer to this as 'this'
  });
});
Run Code Online (Sandbox Code Playgroud)