jQuery在表单元格中找不到输入
我的表格单元格值有一个奇怪的问题 我的HTML就像:jQuery在表单元格中找不到输入,jquery,html,Jquery,Html,我的表格单元格值有一个奇怪的问题 我的HTML就像: <table> <tr> <td> celll </td> <td> celll </td> <td> celll </td> </tr> <tr> <td> celll </td> <td> <input
<table>
<tr>
<td> celll </td>
<td> celll </td>
<td> celll </td>
</tr>
<tr>
<td> celll </td>
<td> <input type='text'> </td>
<td> <input type='text'> </td>
</tr>
</table>
$('table').find('td').each(function(){
if($(this).text()==''){
console.log('found input')
}
})
然而,我似乎找不到它与我的代码
这里有什么提示吗?$(this).text()
会以某种方式“删除”html标记,但会将所有字符作为文本显示在节点中。这将包括空格
在您的示例中,.text()
调用将返回“cell”
(空格-“cell”-space)或”
(空格-space)-如中所示
基于单元格唯一的.text()
值识别单元格确实是一个糟糕的选择。尝试,或尝试向单元格添加一些id
或class
属性,并使用适当的选择器
如果您提供了更多的上下文,可能有人会给您一个更合适的答案。$.text()
方法获取每个元素的组合文本内容,并返回所有空格或新行
因此,您可以使用$修剪字符串。trim
方法:
$('table').find('td').each(function() {
if($.trim($(this).text()) === ''){
console.log('found input');
}
});
更新
另一个选项是再次使用.find()
方法,如下例所示,但是根据我的,使用jQuery 1.8.x,这具有较低的性能:
$('table').find('td').each(function() {
if($(this).find('input').length){
console.log('found input');
}
});
是的,其他人是对的,
文本
可能返回了一些空格
你可以让你的生活变得更轻松,使用它
$('td').has('input');
或者,如果可能的话,其他元素也有一个输入,你可以这样做
$('td').has('input').filter(function(){
return $(this).children() === 1;
});
或者如果你不想坚持你的text
方法,你可以修剪空白
$('td').each(function(){
if( $(this).text().replace(/\s/g, '') === '' ) {
console.log('Input found!');
}
});
演示: