3

我的表格单元格值有一个奇怪的问题。

我的 HTML 就像:

<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>

我想替换有input标签的单元格。

所以我:

 $('table').find('td').each(function(){
      if($(this).text()==''){
          console.log('found input')  

      }
  })

但是,我似乎无法用我的代码找到它。

这里有什么提示吗?

4

3 回答 3

1

$(this).text()会以某种方式“删除”html标签,但它会将所有字符作为文本保留在节点中。这将包括空格。

在您的示例中,.text()调用将返回" cell "(space - "cell" - space) 或" "(space - space) -如此 fiddle所示。

根据其唯一.text()值识别单元格确实是一个糟糕的选择。尝试mithunsatheesh' answer,或尝试向您的单元格添加一些idclass属性,并使用适当的选择器。

如果您提供更多上下文,也许有人可以给您更合适的答案。

于 2013-08-23T20:34:25.053 回答
1

是的,其他人是对的,text可能会返回几个空格。

你可以让你的生活更轻松,使用有。

$('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!');
   }
});

演示:http: //jsfiddle.net/ck6zn/

于 2013-08-23T21:30:50.403 回答
0

$.text()方法获取每个元素的组合文本内容,它还将返回所有空格或换行符。

因此,您可以使用$.trim以下方法修剪字符串:

$('table').find('td').each(function() {
  if($.trim($(this).text()) === ''){
    console.log('found input');  
  }
});

JSBin 演示

更新

另一种选择是.find()再次使用方法作为下面的示例,根据我的JSPerf 测试,使用jQuery 1.8.x,这具有较低的性能:

$('table').find('td').each(function() {
  if($(this).find('input').length){
    console.log('found input');  
  }
});
于 2013-08-23T20:37:26.403 回答