3 回答
TA贡献1811条经验 获得超6个赞
问题是您要附加到名为output. output最初的值为undefined,这就是为什么您会在结果字符串中看到它(在追加之后)。要规避此问题,您可以更改此行:
let output;
对此:
let output = '';
或者,您可以执行类似于下面的操作,其中我使用了mapandjoin而不是附加到自变量。我用setTimeout包裹在 a 中Promise来模拟fetch调用
const ulEl = document.querySelector('.vendorDropdown');
const simulateFetch = () => {
ulEl.innerHTML = 'Fetching JSON. Please wait..';
//Mock data
const json = {
"vendor_name": ["User 1", "User 2", "User 3"]
};
//Promise resolves some JSON data
return new Promise((resolve, reject) => {
setTimeout(() => resolve(json), 1500);
});
};
document.querySelector('button').addEventListener('click', () => {
simulateFetch().then(json => {
//Create the HTML and append it to the ul
const liEls = json['vendor_name'].map(vendor => `<li>${vendor}</li>`);
ulEl.innerHTML = liEls.join(' ')
})
.catch(err => console.error(err));
});
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data- toggle="dropdown">Dropdown Example
<span class="caret"></span></button>
<ul class="dropdown-menu vendorDropdown">
</ul>
</div>
添加回答
举报