JQuery在使用相应的值渲染和替换键之后搜索dom元素 [英] JQuery search dom elements just after rendering and replace keys by its corresponding values
问题描述
我正在尝试在我的开发Web应用程序中应用我自己的本地化方法。
知道我使用的是JQuery 2.2.0,没有任何其他框架或第三方。我需要在我的纯HTML代码中写一些表达式,以便:
I am trying to apply my own localization method on my under development web application. knowing that I am using JQuery 2.2.0, without any other framework or third party. I need to write some expressions in my pure html code such that:
ex-1:
<span>#{{lang.details}}</span>
ex-2:
<button value='#{{lang.save}}'>
然后,一旦dom完全呈现,我想通过dom元素并找出所有这些以#{{并以}}开头的表达式,用我的JSON包中的相应值替换它们。
And then, once the dom is completely rendered, I want to pass through the dom element and find out all these expressions that start with "#{{" and end with "}}", to replace them with the corresponding value in my JSON bundle.
My JSON bundle看起来喜欢:
My JSON bundle looks like:
var en = {
details: "details",
save: "save"
}
我的app.js代码:
My app.js code:
var lang = en;
// jquery load en json file
// search the dom elements and replace the key surrounded
// by '#{{ }}' with its corresponding value from the bundle
在JavaScript或JQuery中找出这些元素的最佳方法是什么。我不能通过第三方获得任何其他解决方案吗?
What is the optimal way to find out these element either in JavaScript or in JQuery. I can't is there any other solution through a third party ?
推荐答案
页面加载后用JavaScript变量替换HTML
Replacing HTML with JavaScript Variables after Page Load
var doneReplacing = false;
$(function() {
if (doneReplacing === false) {
$(document.documentElement).html(function(index, content) {
return content.replace(/#{{([^}]*)}}/g, function(match, $1) {
return eval($1);
});
});
doneReplacing = true;
}
});
基本上它的作用是在页面加载后搜索模式 #{{variable}}
然后将匹配替换为变量的值。
Basically what it does is, after the page loads, it searches for the pattern #{{ variable }}
and then replaces the match with the value of the variable.
这篇关于JQuery在使用相应的值渲染和替换键之后搜索dom元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!