我使用 Javascript 來動態創建很多元素。div、影像、跨度等。
這是我的 JS 將運行的示例代碼:
infoCell.innerHTML = "Submitted by " "<a href='/user/" this.poster "'><img src='" this.poster_avatar_src "' class='avatarimg'> <span style='color:blue'>" this.poster "</span> </a>in " "<span style='color:blue; font-weight: 900;'><a href='/h/" href "'>" this.topic "</a></span>"
這是在我的 JS 開發早期撰寫的,但現在我意識到它很快就會變得非常不安全,因為幾乎所有插入 HTML 的 javascript 變數都是由用戶撰寫的,對字符使用等沒有限制。
我怎樣才能通過我的 javascript 并更改所有這些以使它們仍然起作用,但又不用擔心用戶將腳本插入我的網站?
我很好地重寫了很多,但我不想再這樣做了。我的主 JS 檔案(打字稿)中有大約 90 個 innerHTML DOM 修改。
uj5u.com熱心網友回復:
你可以嘗試使用document.createElement和的組合HTMLElement.append
第一個 <a> 標簽的示例:
function makeElem (tagname, properties) {
let elem = document.createElement(tagname);
for (const key in properties) {
elem[key] = properties[key];
}
return elem;
}
infoCell.append("Submitted by ");
let a = makeElem("a", {href:'/user/"' this.poster '"'});
a.replaceChildren(makeElem("img", {'src':this.poster_avatar_src, 'className':'avatarimg'}), makeElem("span", {'textContent':this.poster,'style':'color:blue;'}));
infoCell.append(a);
這可能不是最簡單的,但它應該可以作業,“makeElem”功能的原因純粹是為了方便,你不一定需要它
uj5u.com熱心網友回復:
有幾種方法。
一種是在插值之前使用消毒劑將所有動態值轉換為正確轉義的字串 - 但你必須確保你做對了,否則可能仍然存在問題。
另一種方法是構造元素結構,然后在適當的點插入動態字串,例如:
const cell = document.createElement('div');
cell.innerHTML = `
Person info
<div class="name"></div>
<div class="age"></div>
`;
cell.querySelector('.name').textContent = name; // where name is dynamic
cell.querySelector('.age').textContent = age; // where age is dynamic
但是,如果您要插入很多動態值,這可能會很乏味。
第三種方法(也是我推薦用于嚴肅應用程式的方法)是使用框架為您處理它。例如,在 React 中,上面的“單元格”可以這樣寫:
const Cell = ({ name, age }) => (
<div>
Person info
<div class="name">{name}</div>
<div class="age">{age}</div>
</div>
);
這需要一些學習和習慣,但是一旦開始,它就比其他方法更容易讀寫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/413745.html
標籤:
上一篇:植物學庫——最快的數字簽名驗證
