javascript - 元素列表后缺少] - Javascript附加方法
问题描述
由于这行 javascript,我正在尝试创建与我的项目相关的动态下拉菜单:
$("#navbar-item-1").append(`<a class="dropdown-item" type="button" onclick="changeMyCurrentMap('${tabName[j]}','${tabLat[j]}','${tabLon[j]}', ${tabMarkerList[j]})">${tabName[j]}</a>`);
当我们单击导航栏(Bootstrap3)中包含的按钮之一时,我们激活了由这个原型表示的 changeMyCurrentMap 函数:
function changeMyCurrentMap(name, lat, lon, markerList);
name,lat和lon分别是一个字符串和 2 个双精度。markerList是一个对象列表。
当我使用 onclick 调用 changeMyCurrentMap 时,所有参数都正确传递,除了返回此错误的数组(所以 markerList):
语法错误:元素列表后缺少 ]。
我已经阅读了很多关于此类错误的帖子,但我仍然找不到我的问题所在。有没有人有任何想法?
解决方案
为了在 HTML 中添加所有值,您可以只编写索引并在回调函数中使用相同的索引。检查两个例子,做同样的事情。一种不使用索引,另一种使用索引。
$(function () {
const tabName = ["tab1", "tab2", "tab3"];
const tabLat = ["tabLat1", "tabLat2", "tabLat3"];
const tabMarkerList = ["tabMarkerList1", "tabMarkerList2", "tabMarkerList3"];
const tabLon = ["tablon1", "tablon2", "tablon3"];
window.changeMyCurrentMap = (name, lat, lon, mark) => {
console.log(name, lat, lon, mark);
};
for (let j = 0; j < 3; j++) {
$("#navbar-item-1").append(
`<li><a class="dropdown-item" type="button" onclick="changeMyCurrentMap('${tabName[j]}','${tabLat[j]}','${tabLon[j]}', '${tabMarkerList[j]}')">${tabName[j]}</a></li>`
);
}
window.changeMyCurrentMapIndex = (index) => {
console.log(
tabName[index],
tabLat[index],
tabLon[index],
tabMarkerList[index]
);
};
for (let j = 0; j < 3; j++) {
$("#navbar-item-2").append(
`<li><a class="dropdown-item" type="button" onclick="changeMyCurrentMapIndex(${j})">${tabName[j]}</a></li>`
);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<p>Without index</p>
<ul id="navbar-item-1"></ul>
<p>With index</p>
<ul id="navbar-item-2"></ul>
推荐阅读
- c++ - 在 C++ 代码中使用字符 `$` 或 `@` 有什么问题吗?
- java - Spring Profile 根据环境自动指定
- azure-data-factory - Azure 复制活动休息结果意外
- javascript - 如何根据字段 OrderNo 和 Location 合并两个对象数组?
- qr-code - 使用 QRCoder 库版本 1.3.5 时无法访问 QRCode 或 QRCodeGenerator.QRCode 类
- java - 如何避免缓存子集合?
- python - 为什么列表理解会删除一个 int?
- bash - 用另一个字符串外壳剥离一个字符串
- docker - Dockerfile apt-get install - 503 服务不可用
- python - 在 Python 中打开和读取文件