querySelector (GetElementByID) - Multiple IDs

前端 未结 2 1691
星月不相逢
星月不相逢 2021-01-29 13:46

i have function to convert gregorian dates to jalali date,its work for one tag,but i have unspecified number of this tags in one page, and it must convert all of theme.

2条回答
  •  盖世英雄少女心
    2021-01-29 14:11

    You made mistakes in your code, also in the DOM, you do not have two elements with the same identifier. The querySelector returns that the first element found, you must instead use querySelectorAll which will return you an array.

    function gregorian_to_jalali(gy,gm,gd){
     g_d_m=[0,31,59,90,120,151,181,212,243,273,304,334];
     if(gy > 1600){
      jy=979;
      gy-=1600;
     }else{
      jy=0;
      gy-=621;
     }
     gy2=(gm > 2)?(gy+1):gy;
     days=(365*gy) +(parseInt((gy2+3)/4)) -(parseInt((gy2+99)/100)) +(parseInt((gy2+399)/400)) -80 +gd +g_d_m[gm-1];
     jy+=33*(parseInt(days/12053)); 
     days%=12053;
     jy+=4*(parseInt(days/1461));
     days%=1461;
     if(days > 365){
      jy+=parseInt((days-1)/365);
      days=(days-1)%365;
     }
     jm=(days < 186)?1+parseInt(days/31):7+parseInt((days-186)/30);
     jd=1+((days < 186)?(days%31):((days-186)%30));
     return [jy,jm,jd];
    }
    
    var dateElement = document.querySelectorAll('.date');
    for(var i = 0; i < dateElement.length; i++) {
      const year = Number(dateElement[i].dataset.year); // "2019"
      const month = Number(dateElement[i].dataset.month); // "2"
      const day = Number(dateElement[i].dataset.day); // "6"
      dateElement[i].textContent = gregorian_to_jalali(year, month, day).join('/');
    }




提交回复
热议问题