【问题标题】:Creating a numbered element with vanilla js使用 vanilla js 创建编号元素
【发布时间】:2019-11-20 05:53:14
【问题描述】:

我正在使用 dom 创建一些 html 元素。确切地说是按钮。我对 javascript 很陌生,所以任何建议都将不胜感激。

我为此使用的 js 基于 div 的节点列表。我正在使用 for 循环创建基于节点列表中每个对象的按钮(每个 div 生成一个按钮)。

这里是js:

let indInit = function(){
	for(i = 0; i < slides.length; i++){
		document.querySelector('.gallery-indicator-nav').innerHTML +=
		'<button class="gallery-indicator" onclick="currentSlide(1)></button>';
	}
};
indInit();

显然,我最终得到了

<div class="gallery-indicator-nav">
<button class="gallery-indicator" onclick="currentSlide(1)></button>
<button class="gallery-indicator" onclick="currentSlide(1)></button>
<button class="gallery-indicator" onclick="currentSlide(1)></button>
</div>

我希望我的按钮生成如下:

<div class="gallery-indicator-nav">
<button class="gallery-indicator" onclick="currentSlide(1)></button>
<button class="gallery-indicator" onclick="currentSlide(2)></button>
<button class="gallery-indicator" onclick="currentSlide(3)></button>
</div>

我假设我需要使用某种排序或数学对象和连接,但至少可以说对谷歌的研究一直令人困惑。我认为必须有一个简单的解决方案 =)

【问题讨论】:

    标签: javascript dom slider innerhtml


    【解决方案1】:

    如果你使用innerHTML,你可以像对待任何其他字符串一样对待它,所以:

    ***.innerHTML = 'xxxxxxx' + i + 'xxxxxx';
    

    可以使用;

    也许您想尝试创建按钮元素并附加一个 EventListener:

    btn = document.createElement(....);
    btn.addEventListener( .... );
    

    【讨论】:

    • 甜蜜。谢谢吴特里!第一个建议成功了。我有一种偷偷摸摸的感觉,这并不复杂。感谢您的帮助和时间,特里!
    【解决方案2】:

    在Terry Wu的建议下:

    for(i = 0; i < slides.length; i++){
    	document.querySelector('.gallery-indicator-nav').innerHTML +=
    	'<button class="gallery-indicator" onclick="currentSlide(' + i + ')"></button>';
    }

    我结束了这个。完美:

    <div class="gallery-indicator-nav">
      <button class="gallery-indicator" onclick="currentSlide(0)"></button>
      <button class="gallery-indicator" onclick="currentSlide(1)"></button>
      <button class="gallery-indicator" onclick="currentSlide(2)"></button>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2021-12-26
      • 2018-05-13
      • 2021-03-11
      • 2021-12-08
      相关资源
      最近更新 更多