香草JS -如何映射字符串数组,并设置按钮的InnerHtml



我在香草JS写一个简单的应用程序。我有一个字符串数组,我想通过数组映射并将innerHTML的值分配给按钮。我可以用。map()来做吗?到目前为止,我能得到的最多的是分配给按钮的innerHTML ('next>')的最后一件事

这是我的代码

var buttons = document.getElementsByTagName("button");
const a = ["click for more", "see more", "details page", "next >"];
a.map((i) => {
buttons.innerHTML = i;
});
<div>
<button>Submit</button>
<button>Submit</button>
<button>Submit</button>
<button>Submit</button>
</div>
<script src="index.js"></script>

你离解决方案很近了。你只需要访问从Array.forEach()

得到的索引数组项注意,Array.map()Array.forEach()取代,因为您不使用map()函数的返回值来创建一个新数组。(感谢@Ivar)

var buttons = document.getElementsByTagName("button");
const a = ["click for more", "see more", "details page", "next >"];
a.forEach((text, index) => {
buttons[index].innerHTML = text;
});
<body>
<div>
<button>Submit</button>
<button>Submit</button>
<button>Submit</button>
<button>Submit</button>
</div>
<script src="index.js"></script>
</body>

您错过了索引按钮

如果你在按钮上使用querySelectorAll,你会得到一个NodeList。forEach,这比使用array。forEach

更有意义

var buttons = document.querySelectorAll("button");
const a = ["click for more", "see more", "details page", "next >"];
buttons.forEach((but, i) => {
but.innerHTML = a[i];
});
<body>
<div>
<button>Submit</button>
<button>Submit</button>
<button>Submit</button>
<button>Submit</button>
</div>
<script src="index.js"></script>
</body>

相关内容

  • 没有找到相关文章