[英]Why isn't my json data loading in the right order using javascript?
我做了一個 chrome 擴展,它從 JSON 文檔中獲取價格並將它們插入到網站中,但是價格以錯誤的順序插入。 該網站是 csgoempire.com/withdraw
我已經嘗試為 chrome.runtime.sendMessage 設置超時,但這只會在開始時延遲它,而不是每次循環運行。
內容.js
function replacePrices() {
let skinNumber = 1;
console.log("Changing Prices");
let prices = document.getElementsByClassName('item__price');
var priceNumber = 0;
for (elt of prices) {
var skinNick = document.getElementsByClassName("px-2");
let skinFullName = skinNick[skinNumber].textContent;
let containsFactoryNew = skinFullName.includes('Factory New');
let containsMinimalWear = skinFullName.includes('Minimal Wear');
let containsFieldTested = skinFullName.includes('Field-Tested');
let containsWellWorn = skinFullName.includes('Well-Worn');
let containsBattleScarred = skinFullName.includes('Battle-Scarred');
let isBundle = skinFullName.includes('Bundle');
if (isBundle === true) {
let price = 'Bundle';
} else {
if (containsFactoryNew === true || containsMinimalWear === true || containsFieldTested === true || containsWellWorn === true || containsBattleScarred === true) {
skinWear = '(' + skinFullName + ')';
skinFullName = '';
} else {
skinFullName = skinFullName.trim();
skinFullName = skinFullName.replace(/\s\s+/g, ' | ');
skinFullName = skinFullName + ' ' + skinWear;
console.log(skinFullName);
chrome.runtime.sendMessage(
{contentScriptQuery: "queryPrice", itemURL: skinFullName},
price => {
prices[priceNumber].innerHTML = prices[priceNumber].innerHTML + ' | ' + price;
prices[priceNumber].style.cssText = 'color: silver; font-size: .8125rem; font-weight: 700; font-family: Lato,sans-serif;';
priceNumber = priceNumber + 1;
});
skinWear = '';
}
}
// http://steamcommunity.com/market/priceoverview/?appid=730¤cy=3&market_hash_name=StatTrak%E2%84%A2 M4A1-S | Hyper Beast (Minimal Wear)
skinNumber = skinNumber + 1;
}
btnReplace.innerHTML = "Reload Steam Market Prices";
}
背景.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.contentScriptQuery == "queryPrice") {
var url = "https://pixelboii.wtf/steamvalue.json";
var skinFullName = request.itemURL;
fetch(url)
.then(res => res.json())
.then(price => {
sendResponse(price.items_list[skinFullName].price["7_days"].average);
})
.catch(err => { throw err });
return true; // Will respond asynchronously.
}
});
價格應該加載,以便它們與它們放置在下面的項目相匹配,但目前,它們相互混淆。 沒有錯誤代碼。
您遇到的問題是並行訪問變量的經典問題。 本質上,發生的情況是每次獲取價格時您的 priceNumber 都會增加 1,但有可能 2 個價格獲取同時返回,同時更新 DOM,然后同時增加,但它們重新使用相同的 priceNumber 值來確定在何處插入其價格。
解決此問題的最簡單方法是同時返回 skinFullName 以及您的價格,然后在 skinFullName 和索引之間設置一個 Map。 這樣,您可以根據 skinFullName 查找固定索引,而無需依賴以與您獲取它們相同的順序到達的皮膚價格獲取(在這種情況下也不能保證)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.