开发者

jQuery Event only firing for first named element

I have hyperlinks, all are named 'mylink'. They should all fire the same event, but only the first element named 'mylink' actually fires. My code is as follows:

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

Where am I going wrong?


You can't re-use an "id" value. A given "id" can only be used once on a page.

If you need multiple elements to be affected, use a "class" component:

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


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


You should change them to a class.

Read this.


I don't know that it's all that much more efficient, but while your in there, it might not be a bad idea to reference that link by element (a#mylink) also, otherwise jquery could have to search the entire document for the class.

 $('a.mylink').click(function(e) { 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜