伙计们,我有以下 JavaScript 函数,它应该检查表中列的索引。问题是列名和表中的名称的比较。 我用columnName 'ID'测试过,在表中找到了该列,但是比较不成立,所以没有返回索引。
我的代码:
function getColumnIndex(columnName, grid) {
console.log("loading column index for column: [" + columnName + "]");
$('div.hDivBox > table > thead > tr > th', grid).each(function(index) {
var name = $(this).attr('title');
console.log("Checking cell: [" + name + "]");
if (String(name) == columnName) {
return index;
}
});
console.log("no cell found with name: " + columnName);
return -1;
}
日志语句:
loading column index for column: [ID]
Checking cell: [ID]
Checking cell: [Name]
Checking cell: [Description]
Checking cell: [AddTime]
Checking cell: [UpdTime]
no cell found with name: ID
由 javascript 函数分析的 HTML 示例:
<div class="hDivBox">
<table cellspacing="0" cellpadding="0">
<thead>
<tr>
<th align="center" hidden="" axis="col0" title="ID" style="display: none;">
<div style="text-align: center; width: 30px;">ID</div>
</th>
<th align="center" axis="col1" title="Name" class="">
<div style="text-align: center; width: 250px;">Name</div>
</th>
<th align="center" axis="col2" title="Description" class="">
<div style="text-align: center; width: 250px;">Beschreibung</div>
</th>
<th align="center" axis="col3" title="AddTime">
<div style="text-align: center; width: 120px;">hinzugefügt</div>
</th>
<th align="center" axis="col4" title="UpdTime">
<div style="text-align: center; width: 120px;">aktualisiert</div>
</th>
</tr>
</thead>
</table>
最佳答案
传递给 .each()
jQuery 函数的匿名函数内的 return
语句仅从 that 函数返回,而不会返回也从 getColumnIndex()
函数返回。
相反,我会执行以下操作:
function getColumnIndex(columnName, grid) {
console.log("loading column index for column: [" + columnName + "]");
var index = -1;
$('div.hDivBox > table > thead > tr > th', grid).each(function(i) {
var name = $(this).attr('title');
console.log("Checking cell: [" + name + "]");
if (String(name) == columnName) {
index = i;
return;
}
});
if(index == -1)
console.log("no cell found with name: " + columnName);
return index;
}
基本原则是,您只需将正确的索引存储在作用域外部的变量中,而不是从匿名函数返回索引,因此您可以在 .each( )
调用已完成执行。
关于javascript - 比较使用 jquery 加载的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11763011/