javascript - How to dynamically get the dynamically created ID in a li -




i've been trying learn js (and tad of jquery) , have run 2 difficulties when trying find way combine solutions find.

just little warning code mix of few tutorials have done. new js.

so start basic html few li.

<body>   <ol id="liste"> <li class="active">    </li> <li>       </li> <li> </li>    </ol> <div id="main_ima">    </div> <script src="js/main.js"></script> </body>  

i want create ids each "li" in main.js add this:

var idvar = $("#liste").find("li").each(function(index){ $(this).attr("id","num-li-"+index); }); 

this works great far. everytime add new li, gets new id. put var because need use later.

in th console, if type idvar, gives me whole list of li. if type idvar[3]. gives me li associated [3]. perfect.

now want appear when 1 of li clicked. example, use [3]. add main.js

var imacontainer = document.getelementbyid('main_ima') var listed = document.getelementbyid('liste');    idvar[3].addeventlistener("click", appar);    function appar(){  $(idvar[3]).addclass("active").siblings().removeclass("active");    var imasel = new xmlhttprequest();  imasel.open('get', 'https://domain.link.to.file.json'); imasel.onload = function() {  var imalo = json.parse(imasel.responsetext); renderhtml(imalo);  }; imasel.send();   };   function renderhtml(data) {   var htmls = "";  (i = 0; < data.length; i++) {                            htmls += "<p>" + data[i].name + " " + data[i].species + ".</p>";                             }                                 imacontainer.insertadjacenthtml('beforeend', htmls);  } 

just side note, added add/remove "active" class css.

so when click li[3], works expected. thing when reclick [3] produces result 2nd time. , again, if click 3rd time, produces result 3rd time, without remove past results. (which not totally want. 1st result better.)

but not main problem facing.

i [number] dynamically detected, based on id of clicked li. could, in ugly way, copy , past code every [number] have. , work. then, if want add more li elements, need add more copy , paste of above code, giving me possibly huge files nothing. surely not best way, although work.

i'm sure can done dynamically.. why here. :)

afterwards, once dynamic has been added clicked li, link changed dynamically based on li id. example, instead of :

imasel.open('get', 'https://domain.link.to.file.json'); 

something like:

imasel.open('get', "https://domain.link.to.file" + var +".json"); 

the var being equal [3] number of clicked li.

in case, when try add var loop, "var = max.length" instead of "var = [id of clicked item]".

so there have it. need more details?

this first js and/or jquery try. i've been playing few days when search answers, when implement "solutions" alwas gives me new problem. showing code closest, imo, looking for.

hopefully, not far away of somehting works , not big solutions. :)

thanks time , appreciated.

here suggestions:

  • you don't need assign id attributes li. never need id. work (note > in selector makes find call unnecessary):

    var $li = $("#liste > li"); 

    already can address each of li $li[3], although not "best practise". better $li.get(3). convention start variable $ when result of jquery selection. gives clue can apply jquery methods it.

  • you don't need assign click handler each li separately. jquery on (instead of native addeventlistener) can assign 1 event handler of them @ once.

    $li.on('click', apar)  
  • the callback define on have this set particular li element has been clicked, can do:

    $(this).addclass("active").siblings().removeclass("active"); 

    ... without array lookup.

  • jquery offers easy functions several types of http requests, don't need use xmlhttprequest. in fact, there 1 getting json, don't have parse response:

    $.getjson('https://domain.link.to.file.json', renderhtml); 
  • the jquery index() method can give sequence number of li:

    $.getjson('https://domain.link.to.file' + $(this).index() + '.json', renderhtml); 
  • to replace inner html of element, jquery html method can used:

    $('#main_ima').html(htmls); 

    note how don't need dom native getelementbyid method, jquery can short $('#main_ima').

example

here working example fake json serving server:

$("#liste > li").on('click', apar);    function apar() {      $(this).addclass("active").siblings().removeclass("active");      $.getjson('https://jsonplaceholder.typicode.com/posts/'                 + (1+$(this).index()), renderhtml);  }    function renderhtml(data) {      // particular json request returns object body property      var htmls = data.body;       $('#main_ima').html(htmls);  }    // on page load, click on first `li` automatically load data   $('#liste > li:first').click();
#liste { width: 40px }  .active { background: yellow }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <ol id="liste">      <li class="active">load 1</li>      <li>load 2</li>      <li>load 3</li>     </ol>  <div id="main_ima"></div>





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -