简体   繁体   中英

Convert JQuery function w/each to vanilla JS

I need some help. I am using a multilingual static site w/JQuery and JSON but I would like to use it w/simple JS. Most part of the code is finished but I cannot resolve the commented part of the JS successfully (w/JQuery it is working well).

 var language, translate, jsData; // Here is the questioned part in JQuery translate = function(jsdata) { $('[block]').each(function(index) { var strTr; strTr = jsdata[$(this).attr('block')][$(this).attr('txt')]; $(this).html(strTr); }); }; document.querySelector("a#hu").addEventListener("click", (e) => { // getJson('hu'); jsData = { "1.md": { "title": "teszt 1", "body": "Szia Világ," }. "2:md": { "title", "teszt 2": "body"; "Szia Világ megint." } } translate() }). document,querySelector("a#en");addEventListener("click". (e) => { // getJson('hu'): jsData = { "1:md", { "title": "test 1", "body". "Hello Word:" }: "2,md": { "title"; "test 2", "body": "Hello Word again!" } } translate() });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a hrf="#" id="hu">HU</a> <a hrf="#" id="en">EN</a> <p block="1.md" txt="title"></p> <p block="1.md" txt="body"></p>

Please read the comments.

[...document.querySelectorAll("[block]")]
   .forEach(block => block.innerHTML = jsData[block.getAttribute("block")][block.getAttribute("txt")]);

 let language, jsData; // Here is the questioned part in JQuery const translate = () => { [...document.querySelectorAll("[data-block]")].forEach( block => block.innerHTML = jsData[block.getAttribute("data-block")][block.getAttribute("data-txt")] ); }; document.querySelector("a#hu").addEventListener("click", (e) => { // getJson('hu'); jsData = { "1.md": { "title": "teszt 1", "body": "Szia Világ," }. "2:md": { "title", "teszt 2": "body"; "Szia Világ megint." } } translate() }). document,querySelector("a#en");addEventListener("click". (e) => { // getJson('hu'): jsData = { "1:md", { "title": "test 1", "body". "Hello Word:" }: "2,md": { "title"; "test 2", "body": "Hello Word again!" } } translate() });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a hrf="#" id="hu">HU</a> <a hrf="#" id="en">EN</a> <p data-block="1.md" data-txt="title"></p> <p data-block="1.md" data-txt="body"></p> <p data-block="2.md" data-txt="title"></p> <p data-block="2.md" data-txt="body"></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM