Portál AbcLinuxu, 11. května 2025 06:37
Ahoj, kod jsem maximalne zjednodusil, ma delat to, ze mam DIV rules_1 a rules_2, ma se nacist INI soubor, ktery obsahuje X parametru pro rules_1 a X parametru pro rules_2, ty parametry ma dynamicky vlozit do DIV rules_1 a rules_2. Priklad by mel do rules_1 vytvorit 1 pravidlo a k hodnote input pridat 'ok'. Do rules_2 by mel vytvorit 2 pravilda a pridat do input 'ok', ale prvni input se nezmeni, kdyz se divam do konzole, tak vypisuje, ze input se zmenil, ale v prohlizeci neni input aktualizovan.
<div id="rules_1"></div>
<div id="rules_2"></div>
<script> var initVal=0; function addRule (idx){ initVal++; let dest = document.getElementById ('rules_' + idx); dest.innerHTML += '<input type=text value="' + initVal + '" class="Rule_' + idx + '_DTValue"><br>'; } function load (){ let ini = {}; ini['Rule_1'] = {}; ini['Rule_1']['OutputIdx'] = 1; ini['Rule_2'] = {}; ini['Rule_2']['OutputIdx'] = 2; ini['Rule_3'] = {}; ini['Rule_3']['OutputIdx'] = 2; for (let i=1; i<=100; i++){ if (ini['Rule_' + i] == undefined) break; let PIdx = ini['Rule_' + i]['OutputIdx']; addRule (PIdx); elm = document.getElementsByClassName ('Rule_' + PIdx + '_DTValue'); console.log (elm[elm.length - 1].value); elm[elm.length - 1].value = elm[elm.length - 1].value + ' ok'; console.log (elm[elm.length - 1].value); } } load (); </script>
Řešení dotazu:
dest.innerHTML += ...
"vymaže" zmenu vo value atribúte. Na pridanie nových elementov sa dá použiť niečo ako createElement + appendChild.
dest.insertAdjacentHTML('beforeend', '...')
<script> class showRules { constructor(root) { let el=document.getElementById(root); el.innerHTML=''; this.root=root; } create_line(rule){ let line=document.createElement("div"); line.classList.add("line"); let el=document.createElement("span"); el.innerHTML=rule; line.append(el); el=document.createElement("button"); el.innerHTML="OK"; line.append(el); return line; } add_rule_1 (rule){ let section=document.getElementById(this.root+"_1"); let line=this.create_line(rule); section.append(line); } add_rule_2 (rule){ let section=document.getElementById(this.root+"_2"); let line=this.create_line(rule); section.append(line); } } shower=new showRules("show_rules"); shower.add_rule_1("test A"); shower.add_rule_1("test B"); shower.add_rule_2("test C"); <<script>Ak potrebuješ ukládať nejaké dáta k nejakému elementu, tak nemusíš ukladať do array, ale môžeš použiť .dataset v JS
<pre class="brush: html"><div>Hello world</div></pre>
Stejna chyba (znacka SCRIPT neni povolena) Jenom jsem mezi PRE vlozil SCRIPT
<pre class="html brush:"><script></pre>
Oprava:
<pre class="brush: html"><script></pre>
<pre class="brush: html"><script>document.write("Hello world");</script></pre>A vystup:
<pre class="brush: html"><script>document.write("Hello world");</script></pre>Znak < musíš zakódovať ako HTML entitu.
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.