![](/img/trans.png)
[英]How to avoid unnecessary re-render in other child when I only make change in specific child
[英]How to re-render only specific data on radio button change JS/AJAX
所以我對 AJAX 還是很陌生。 我有一個data.json
文件,從中檢索對象數組。 每個 object 都有一個time
密鑰。 它看起來像這樣:
[
{
"time": 3
},
{
"time": 35
}
]
現在,我有兩個來自引導程序的單選按鈕。 一個說“分鍾”,一個說“秒”。 我想顯示該數據的時間data.json
默認以分鍾為單位,然后當用戶更改為“秒”時,它會在不刷新頁面的情況下重新呈現。 我一直在 React 中處理類似的事情,但我不確定如何使用 vanilla JS 和 AJAX 來做。
我的<body>
看起來像這樣:
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-secondary active">
<input type="radio" name="options" id="option1" checked> Minutes
</label>
<label class="btn btn-secondary">
<input type="radio" name="options" id="option2"> Seconds
</label>
</div>
<div id="render-here">
</div>
<script type="text/javascript">
const xhr = new XMLHttpRequest();
const container = document.getElementById('render-here');
function renderPrice(time) {
return `<span class="price-currency-char"></span><span class="price-value">${time}</span>`;;
}
xhr.onload = function() {
const res = JSON.parse(this.responseText);
for(let i = 0; i < res.length; i++) {
let item = res[i];
container.insertAdjacentHTML('beforeend', `
${renderPrice(item.time)}<br/>
`)
}
};
xhr.open('get', 'data.json');
xhr.send();
</script>
因此,在onload
加載 function 中,我獲取數據並使用 for 循環動態呈現它。
我希望我能很好地解釋一切並提供所有必要的信息。 如果您需要更多信息,請告訴我!
我個人會使用 fetch,因為它更容易使用。 使用 fetch,您首先使用 .json .json()
方法將源解釋為 JSON,然后使用該數據。 因為它是一個數組,我發現在這里使用.forEach()
方法更容易讓我在一行中執行整個有趣的動作。
舉例來說,我將您的示例數組數據上傳到 PasteBin 以從我的 fetch 中提取,以便您可以看到它的運行情況。 這應該有效:
const container = document.getElementById('render-here'); const renderPrice = time => `<span class="price-currency-char"></span><span class="price-value">${time}</span>`; const calculate = () => { container.innerHTML = ""; const multiplier = parseInt(document.querySelector('input[name="options"]:checked').dataset.multipler); fetch('https://pastebin.com/raw/PBkVKmsQ').then(response => response.json()).then(data => data.forEach(item => container.insertAdjacentHTML('beforeend', `${renderPrice(item.time * multiplier)}<br/>`))); }; calculate(); document.addEventListener('change', e => { if (e.target?.matches('input[name="options"]')) calculate(); })
<div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary active"> <input type="radio" name="options" id="option1" data-multipler="1" checked> Minutes </label> <label class="btn btn-secondary"> <input type="radio" name="options" id="option2" data-multipler="60"> Seconds </label> </div> <div id="render-here"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.