我需要一些帮助。我使用的是一个多语言静态网站,带有JQuery和JSON,但我想使用它和简单的JS。大部分代码已经完成,但我无法成功解析JS的注释部分(通过JQuery,它运行良好(。
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>
请阅读评论。
[...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>