我正在使用node + electron構建桌面應用程序。我需要一種方法來容納我在DOM中的UI元素。在前端解析HTML是不是很糟糕的形式?
我想出了可以被其他Typescript DOM元素擴展的解決方案。
我的代碼有效運行。這是否合適使用Typescript?
我在改寫其他人已經寫過的圖書館嗎? 我沒有使用React,因爲它不允許對象範圍的全局變量。
在前端解析HTML是不是很糟糕的形式?
class Glyph {
//field
uuid:string;
//constructor
constructor(parent:string, html:string) {
this.uuid = this.guid();
var regex = /(<([^>]+>))/ig
var tags = html.match(regex);
var position = tags[0].search(/>/ig);
tags[0] = [tags[0].slice(0, position), ' id="'+ this.uuid +'"', tags[0].slice(position)].join('');
html = tags.join('');
//appends child to the provided parent id
document.getElementById(parent).innerHTML += html;
}
guid():string {
return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' +
this.s4() + '-' + this.s4() + this.s4() + this.s4();
}
s4():string {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
replaceElement(html):void {
var currentElement = document.getElementById(this.uuid);
currentElement.outerHTML = html;
}
deleteElement():void {
var child = document.getElementById(this.uuid);
var parent = document.getElementById(this.uuid).parentElement;
parent.removeChild(child);
}
}
https://stackoverflow.com/a/1732454/1687909 – Mogzol
瀏覽器實際上是一個HTML解析器 –
React不允許對象範圍的全局變量?你是什麼意思? – azium