开发者

Can jQuery run a loop?

I am using jQuery to allow my users to quickly go through their profiles. They have an inbox on their profiles and I am letting them delete past messages using jQuery. The problem is that each time the page is loaded there will be a different number of emails. How can I tell jQuery to manage the function for mail1 and mail2 and mail 3 etc but only if they exists.

Below you will see the jquery I am running for each but there needs to be a loop of some kind.

$(document).ready(function() {
  $("#del1").click(function() {
    $(".mail1").fadeOut();
  });
});

$(document).ready(function() {
  $("#del2").click(function() {
   开发者_JAVA技巧 $(".mail2").fadeOut();
  });
});


You should make your elements and code more generic. For instance, give all delete links the same class, lets say deleteButton and all mails the same class, say mail.

Then use their proximity to deal with them. Maybe something like this:

$(".deleteButton").click(function(){
   $(this).parent().find(".mail").fadeOut();
});

This assumes that the button and the mail share a common parent, but even if they don't, something similar can be done.


Give each delete button a common class, and a data-id attribute. You can bind the click event to each del button, then delete the corresponding mail element.

$(".del").click(function() {
    var id = $(this).attr("data-id");
    $(".mail" + id).fadeOut();
});


I'd try something like this:

$("[id^='del']").each(function(){
 $(this).click(function(){
  $('.mail'+(/\d+/).exec($(this).attr("id"))).fadeOut();
 });
});


  1. Bind a click event to all of the del elements.

  2. When they are clicked, get the ID and use it to get the name of the relevant class to be hidden.

  3. Use that class name to do the fadeOut()


I think something like this should work:

$(document).ready(function() {
  $("[id^=del]").each(function(){
    var e=$(this),m = e.attr('id').match(/^del(\d+)$/);
    if( m ){
      e.click(function(){$('#.mail'+m[1]).fadeOut();});
    }
  });
});


$(document).ready(function() {
    if($("#del1").length){
      $("#del1").click(function() {
        $(".mail1").fadeOut();
      });
    }
    if($("#del2").length){
      $("#del2").click(function() {
        $(".mail2").fadeOut();
      });
    }
    ....
});


Jquery allows you to select with 'startswith' you could also use jquery's regex selector but I think this gets you close:

$(document).ready(function() {
  $('*[id^="del"]').click(function() {
    $(this).closest('[class^="mail"]').fadeOut();
  });
});

This assumes that class="mail..." is an ancestor at some point of id="del..."

Since we don't know your exact HTML I like closest instead of parent since parent assumes that del is one layer directly inside of mail.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜