首页 > 解决方案 > 元素列表后缺少] - 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);

namelatlon分别是一个字符串和 2 个双精度。markerList是一个对象列表。

当我使用 onclick 调用 changeMyCurrentMap 时,所有参数都正确传递,除了返回此错误的数组(所以 markerList):

语法错误:元素列表后缺少 ]。

我已经阅读了很多关于此类错误的帖子,但我仍然找不到我的问题所在。有没有人有任何想法?

标签: javascripthtmljquery

解决方案


为了在 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>


推荐阅读