0

我有这张桌子...

<table width="100%" border="0" cellspacing="0" cellpadding="0" class="test-class"> 
 <tr> 
  <td rowspan="6">TEST123<script type="text/javascript">if(window.VCompare){VCompare('TEST123', 4);}</script></td>
  <td rowspan="6"><img src="/images/clear1x1.gif" width="5" height="5"></td> 
  <td rowspan="6" background="/images/test.gif"><img src="/images/clear1x1.gif" width="1" height="1"></td>
  <td rowspan="4"><img src="/images/clear1x1.gif" width="5" height="5"></td>
  <td colspan="9"><img src="/images/clear1x1.gif" width="5" height="5"></td>
 </tr> 
</table>

我需要在没有脚本标签的情况下获取第一个单元格的值,然后在我获得文本的第一个单元格之前添加一个单元格。我试过像..

var matchtext = "TEST123";
jQuery("tr").each(function() {
 var data = jQuery(this).find("td:eq(0)").text();
 var data = jQuery.trim(data);
 if (data == matchtext){
    jQuery(this).before("<td class='testclass' rowspan='6'>test inserted!</td>");
 }
});

并在桌子上循环,但那个脚本让我失望。

4

2 回答 2

0

尝试换行:

if (data == matchtext){

if (data.match(matchtext)) {
于 2013-03-22T16:14:20.263 回答
0

如果您登录data到 firebug 控制台,您会看到字符串是“TEST123if(window.VCompare){VCompare('TEST123', 4);}”,而不仅仅是“TEST123”,因为 javascript 部分也算作文本。

将 JS 部分移出表格,请参阅此小提琴

<table width="100%" border="0" cellspacing="0" cellpadding="0" class="test-class"> 
 <tr> 
  <td rowspan="6">TEST123</td>
  <td rowspan="6"><img src="/images/clear1x1.gif" width="5" height="5"></td> 
  <td rowspan="6" background="/images/test.gif"><img src="/images/clear1x1.gif" width="1" height="1"></td>
  <td rowspan="4"><img src="/images/clear1x1.gif" width="5" height="5"></td>
  <td colspan="9"><img src="/images/clear1x1.gif" width="5" height="5"></td>
 </tr> 
</table>
<script type="text/javascript">if(window.VCompare){VCompare('TEST123', 4);}</script>

此外,您的 JS 代码并不完全符合您的预期,工作代码:

var matchtext = "TEST123";
$("tr").each(function() {
 var $this = $(this),
     data = $.trim($this.children(':first-child').text());

 if (data == matchtext){
     $this.prepend("<td class='testclass' rowspan='6'>test inserted!</td>");
 }
});
于 2013-03-22T16:21:25.327 回答