如何将数组中的表安排到原型?

时间:2013-01-08 08:09:40

标签: javascript arrays prototype

所以,我想修改数组,以便它一次一行地在表中显示其内容。使用下面的代码,它逐步显示代码,每个元素出现多次。

如何解决这个问题? THX。

$(function() {

Array.prototype.ToTable=function(){

tabelul="<center><table border><tr>";

for(a=0; a<this.length;a++){

this[a]=tabelul+="<td> <div class='Expresion'>" + this[a] + "</div></td></tr>"
}


}

vaz=['one', 'two', 'three','four'];


vaz.ToTable();

$('#show').html(vaz)
})

<div id="show"></div>

1 个答案:

答案 0 :(得分:1)

我相信你打算做的事情就是这样:

for(a=0; a<this.length;a++){
 tabelul+="<tr><td><div class='Expresion'>" + this[a] + "</div></td></tr>";
}

您应该构建tabelul变量,然后将其返回。

以下是这样做的一个例子

以下是演示:http://jsfiddle.net/2zchT/2/

HTML:

<div id="show"></div>

JS:

$(function() {
 Array.prototype.ToTable=function(){
  var tabelul = "<center><table border>";
  for(var a=0; a<this.length;a++){
   tabelul += "<tr><td><div class='Expresion'>" + this[a] + "</div></td></tr>"
  }
  tabelul += "</table></center>";
  return tabelul;
 };
 vaz=['one', 'two', 'three','four'];
 $('#show').html(vaz.ToTable())
})

修改

在构建表之前,您应该将数据播种。

var Links= new Array(); 
Links[0]='<a href="http://location.com/"><img src="http://photo1.com/"></a>'; 
Links[1]='<a href="http://location.com/"><img src="http://photo2.com/"></a>'; 
Links[2]='<a href="http://location.com/"><img src="http://photo3.com/"></a>'; 
Links[3]='<a href="http://location.com/"><img src="http://photo4.com/"></a>'; 
Links[4]='<a href="http://location.com/"><img src="http://photo5.com/"></a>';

var vaz=['one', 'two', 'three','four'];

for( var i = 0; i < vaz.length; i++ )
{
 vaz[i] = Links[i] + vaz[i];
}

以下是演示:http://jsfiddle.net/2zchT/4/