[英]Accessing table cells with jQuery using an object
我需要在多维数组中复制表格的单元格。 我尝试以下代码:
function tableManager ( table, rowitems ) {
var items = array () ;
var j = 0 ;
var arow = array() ;
$(table+' td').each(function() {
arow[j] = $(this).html() ;
j ++ ;
if ( j == rowitems) {
items.push(arow);
j = 0 ;
} ;
}) ;
this.show = function() {
.............
}
}
构造函数是:
$(document).ready(function(){
var loadarr = new tableManager ( '#results', 4 ) ;
....
});
似乎不执行each()
回调。
什么不对?
tableManager是一个函数,您不必使用“ new”构造它。 您必须按以下方式调用它:
$(document).ready(function(){
var loadarr = tableManager('#results', 4);
...
});
另外,您还有一个“;” 在您的“ if(...){..}”之后。 您必须将其删除:
if ( j == rowitems) {
items.push(arow);
j = 0 ;
} ; <= REMOVE THIS
此处有更多详细信息: https : //www.w3schools.com/js/js_function_definition.asp
安德烈
如果问题是:
似乎不执行each()回调。
这是因为tableManager
是一个函数,您必须通过以下方式调用它:
var loadarr = tableManager ( '#results', 4 ) ;
有关更多信息,请访问W3Schools。
另外,删除;
if ( j == rowitems)
括号后
if ( j == rowitems) {
items.push(arow);
j = 0 ;
} // Removed ;
更新
如果未达到each
方法,请尝试了解正在发生的事情。 尝试使用
console.log($(table+' td'));
在确保each
方法都不会执行(因为没有元素)之前。
console.log($(table+' td'));
$(table+' td').each(function() {
arow[j] = $(this).html() ;
...
然后,您可以在参数函数中添加console.log("Each executed")
execute console.log("Each executed")
以确保它被执行:
$(table+' td').each(function() {
console.log("Each executed");
arow[j] = $(this).html() ;
j ++ ;
if ( j == rowitems) {
items.push(arow);
j = 0 ;
}
}) ;
您的jquery函数不正确,请参见此处的工作代码
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<table id="results">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</table>
</body>
<script type="text/javascript">
function tableManager ( table, rowitems ) {
var items = [] ;
$(table+' tr').each(function(i) {
var row = $(this);
if(rowitems == i){
row.find('td').each(function() {
console.log(this);
items.push($(this).html());
}) ;
}
});
console.log(items);
return items;
}
var itm = tableManager("#results", 4);
console.log(itm);
</script>
</html>
我希望这能帮到您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.