通过循环动态显示html元素 [英] Dynamically display html elements via loop

查看:144
本文介绍了通过循环动态显示html元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用javascript和jquery。我希望能够按循环次数显示一个按钮,一些文本和/或任何html元素或组件。我可以循环并打印警报语句。

 函数LoopTest(){
var i = 0;
var stop = 5;
for(i = 0; i <5; i ++)
{alert(count:+ i); }
}

足够简单。这会给我5个警报语句,但我不想使用警报语句,而是希望能够显示一个按钮或一些文本或任何其他html元素。所以我会得到五个按钮显示在一个HTML页面上。这可能吗?我实际上使用.foreach函数,但为了便于使用,现在正常的for循环就足够了。我希望能够在点击按钮时执行此操作(即,单击按钮后循环开始运行的功能)。我只是不确定如何做到这一点。任何帮助将不胜感激。

noreferrer> vanilla Javascript (不使用jQuery):

您可以使用 document.createElement 来在页面上创建任何类型的元素。上面的循环在< div> 中创建< INPUT TYPE ='BUTTON'> 元素, id test

  function LoopTest(){
var i = 0;
var stop = 5;
for(i = 0; i <5; i ++){
var v = document.createElement('input');
v.type =button;
v.value =Button+ i;
document.getElementById('test')。appendChild(v);




$ b $(通常,使用document.write已被考虑现在一个不好的练习



使用jQuery,您可以:

  for(i = 0; i< ; 5; i ++){
var btn = $(< button />);
btn.text('Button'+ i);
$('#test')。append(btn);
}


I am working with javascript and jquery. I want to be able to display a buttom, some text, and/or really any html elements or components as many times as the loop allows. I am able to loop through and print alert statements

function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++)
{  alert("count: " + i);   }
}

Simple enough. This would give me 5 alert statements, but instead of using alert statements, I want to be able to display a button or some text or any other html elements. So I would get five buttons displayed on an html page. Is this possible? I'm actually using a .foreach function but for ease of use, a regular for loop would suffice for now. I want to be able to do this on button click (i.e., the function that has the loop starts running once I click a button) also. I'm just not sure really how to accomplish this. Any help would be greatly appreciated. Thanks in advance.

解决方案

With vanilla Javascript (without using jQuery):

You can use document.createElement to create any type of element you want on the page. Here's the above loop creating <INPUT TYPE='BUTTON'> elements in a <div> with an id of test:

function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++) {  
 var v = document.createElement('input');
 v.type="button";
 v.value="Button " +i;
 document.getElementById('test').appendChild(v);
}
}

(In general, using document.write has been considered a bad practice for a while now.)

With jQuery, you can do:

for (i=0;i<5;i++) {  
 var btn = $("<button/>");
 btn.text('Button '+i);
 $('#test').append(btn);
}

这篇关于通过循环动态显示html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆