使用 jquery 动态设置 colspan

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1294850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:08:03  来源:igfitidea点击:

Set colspan dynamically with jquery

jqueryhtml-table

提问by Terry Marder

I have a simple table structure like this. What I would like to do is to dynamically merge some columns based on some condition within the <td>for example, if td1 and td3 are empty then merge the cells and do <td class="col1" colspan="3">1Meeting</td>I tried playing around with jquery using:

我有一个像这样的简单表结构。我想要做的是根据<td>例如中的某些条件动态合并一些列,如果 td1 和 td3 为空,则合并单元格, <td class="col1" colspan="3">1Meeting</td>我是否尝试使用 jquery 进行操作:

 $(".tblSimpleAgenda  td:contains('')").hide();

but it had not the effect.

但它没有效果。

What would be the the best way using jquery to achieve this.

使用 jquery 实现这一目标的最佳方法是什么。

<table  class="tblSimpleAgenda" cellpadding="5" cellspacing="0">
 <tbody>
 <th align="left">Time</th>
 <th align="left">Room 1</th>
 <th align="left">Room 2</th>
 <th align="left">Room 3</th> 

        <tr valign="top">
            <td class="colTime">09:00 – 10:00</td>
            <td class="col1"></td>
            <td class="col2">Meeting 2</td>
            <td class="col3"></td>
        </tr>

        <tr valign="top">
            <td class="colTime">10:00 – 10:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3">Meeting 3</td> 
        </tr>

        <tr valign="top">
            <td class="colTime">11:00 – 11:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3">Meeting 3</td> 
        </tr>
</tbody>
</table> 

回答by Russ Cam

How about

怎么样

$([your selector]).attr('colspan',3);

I would imagine that to work but have no way to test at the moment. Using .attr()would be the usual jQuery way of setting attributes of elements in the wrapped set.

我认为这可行,但目前无法进行测试。使用.attr()将是在包装集中设置元素属性的常用 jQuery 方式。

As has been mentioned in another answer, in order to get this to work would require removing the td elements that have no text in them from the DOM. It may be easier to do this all server side

正如在另一个答案中提到的那样,为了使其工作,需要从 DOM 中删除没有文本的 td 元素。在所有服务器端执行此操作可能更容易

EDIT:

编辑:

As was mentioned in the comments, there is a bug in attempting to set colspan using attr() in IE, but the following works in IE6 and FireFox 3.0.13.

正如评论中提到的,尝试在 IE 中使用 attr() 设置 colspan 存在错误,但以下在 IE6 和 FireFox 3.0.13 中有效。

Working Demo

工作演示

notice the use of the attribute colSpanand not colspan- the former works in both IE and Firefox, but the latter does not work in IE. Looking at jQuery 1.3.2 source, it would appear that attr()attempts to set the attribute as a property of the element if

注意属性的使用colSpan而不是colspan- 前者在 IE 和 Firefox 中都有效,但后者在 IE 中不起作用。查看 jQuery 1.3.2 源代码,似乎attr()尝试将属性设置为元素的属性,如果

  1. it exists as a property on the element (colSpanexists as a property and defaults to 1 on <td>HTMLElements in IE and FireFox)
  2. the document is not xml and
  3. the attribute is none of href, src or style
  1. 它作为元素上的属性存在(作为属性colSpan存在,<td>在 IE 和 FireFox 中的 HTMLElements上默认为 1 )
  2. 该文档不是 xml 并且
  3. 该属性不是 href、src 或 style

using colSpanas opposed to colspanworks with attr()because the former is a property defined on the element whereas the latter is not.

usingcolSpan与 work colspanwith相反,attr()因为前者是在元素上定义的属性,而后者不是。

the fall-through for attr()is to attempt to use setAttribute()on the element in question, setting the value to a string, but this causes problems in IE (bug #1070 in jQuery)

失败的原因attr()是尝试setAttribute()在有问题的元素上使用,将值设置为字符串,但这会导致 IE 出现问题(jQuery 中的错误 #1070)

// convert the value to a string (all browsers do this but IE) see #1070
elem.setAttribute( name, "" + value ); 

In the demo, for each row, the text in each cell is evaluated. If the text is a blank string, then the cell is removed and a counter incremented. The first cell in the row that does not have class="colTime"has a colspan attribute set to the value of the counter + 1 (for the span it occupies itself).

在演示中,对于每一行,评估每个单元格中的文本。如果文本是空字符串,则删除单元格并递增计数器。行中没有的第一个单元格class="colTime"的 colspan 属性设置为计数器的值 + 1(对于它自己占用的跨度)。

After this, for each row, the text in the cell with class="colspans"is set to the colspan attribute values of each cell in the row from left to right.

此后,对于每一行,单元格中的文本class="colspans"从左到右设置为该行中每个单元格的 colspan 属性值。

HTML

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #000; font: 16px Helvetica, Arial; color: #fff; }
td { text-align: center; }
</style>
</head>
<body>
<table  class="tblSimpleAgenda" cellpadding="5" cellspacing="0">
 <tbody>
        <tr>
            <th align="left">Time</th>
            <th align="left">Room 1</th>
            <th align="left">Room 2</th>
            <th align="left">Room 3</th> 
            <th align="left">Colspans (L -> R)</th>
        </tr>
        <tr valign="top">
            <td class="colTime">09:00 – 10:00</td>
            <td class="col1"></td>
            <td class="col2">Meeting 2</td>
            <td class="col3"></td>
            <td class="colspans">holder</td>
        </tr>

        <tr valign="top">
            <td class="colTime">10:00 – 10:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3">Meeting 3</td>    
             <td class="colspans">holder</td> 
        </tr>

        <tr valign="top">
            <td class="colTime">11:00 – 11:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3">Meeting 3</td>
            <td class="colspans">holder</td>     
        </tr>

        <tr valign="top">
            <td class="colTime">11:00 – 11:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3"></td>
            <td class="colspans">holder</td>     
        </tr>
</tbody>
</table>

</body>
</html>

jQuery code

jQuery 代码

$(function() {

  $('table.tblSimpleAgenda tr').each(function() {
    var tr = this;
    var counter = 0;

    $('td', tr).each(function(index, value) {
      var td = $(this);

      if (td.text() == "") {
        counter++;
        td.remove();
      }
    });

    if (counter !== 0) {
      $('td:not(.colTime):first', tr)
        .attr('colSpan', '' + parseInt(counter + 1,10) + '');
    }
  });

  $('td.colspans').each(function(){
    var td = $(this);
    var colspans = [];

    td.siblings().each(function() {
      colspans.push(($(this).attr('colSpan')) == null ? 1 : $(this).attr('colSpan'));
    });

    td.text(colspans.join(','));
  });

});

This is just a demonstration to show that attr()can be used, but to be aware of it's implementation and the cross-browser quirks that come with it. I've also made some assumptions about your table layout in the demo (i.e. apply the colspan to the first "non-Time" cell in each row), but hopefully you get the idea.

这只是一个演示,表明attr()可以使用它,但要注意它的实现和它带来的跨浏览器怪癖。我还在演示中对您的表格布局做了一些假设(即,将 colspan 应用于每行中的第一个“非时间”单元格),但希望您能理解。

回答by Marcos Buarque

I have adapted the script from Russ Cam (thank you, Russ Cam!) to my own needs: I needed to merge any columns that had the same value, not just empty cells.

我已经根据自己的需要改编了 Russ Cam(谢谢你,Russ Cam!)的脚本:我需要合并任何具有相同值的列,而不仅仅是空单元格。

This could be useful to someone else... Here is what I have come up with:

这可能对其他人有用......这是我想出的:

jQuery(document).ready(function() {

   jQuery('table.tblSimpleAgenda tr').each(function() {
    var tr = this;
    var counter = 0;
    var strLookupText = '';

    jQuery('td', tr).each(function(index, value) {
      var td = jQuery(this);

      if ((td.text() == strLookupText) || (td.text() == "")) {
        counter++;
        td.prev().attr('colSpan', '' + parseInt(counter + 1,10) + '').css({textAlign : 'center'});
        td.remove();
      }
      else {
        counter = 0;
      }

      // Sets the strLookupText variable to hold the current value. The next time in the loop the system will check the current value against the previous value.
      strLookupText = td.text();

    });

  });

});

回答by T.J. Crowder

You've said rowspan in your title, but I get the impression you meant colspan; apologies if the below is off because I've got that wrong.

您在标题中提到了 rowspan,但我的印象是您的意思是 colspan;如果以下内容关闭,请道歉,因为我弄错了。

You'd need to remove the blank table cell element entirely, and change the colspan attribute on another cell in the row to encompass the released space, e.g.:

您需要完全删除空白表格单元格元素,并更改行中另一个单元格的 colspan 属性以包含释放的空间,例如:

refToCellToRemove.remove();
refTocellToExpand.colspan = 4;

Note that setting it via setAttribute (which would otherwise be correct) will not work properly on IE.

请注意,通过 setAttribute(否则将是正确的)设置它在 IE 上将无法正常工作。

Beware: IE does some very strange table layout things when you muck about with colspans dynamically. If you can avoid it, I would.

当心:当你动态地使用 colspan 时,IE 会做一些非常奇怪的表格布局事情。如果你能避免它,我会的。

回答by JayCrossler

I've also found that if you had display:none, then programmatically changed it to be visible, you might also have to set

我还发现,如果您有 display:none,然后以编程方式将其更改为可见,您可能还必须设置

$tr.css({display:'table-row'});

rather than display:inline or display:block otherwise the cell might only show as taking up 1 cell, no matter how large you have the colspan set to.

而不是 display:inline 或 display:block 否则单元格可能只显示为占用 1 个单元格,无论您将 colspan 设置为多大。

回答by John Magnolia

Setting colspan="0"is support only in firefox.

设置colspan="0"仅在 Firefox 中支持。

In other browsers we can get around it with:

在其他浏览器中,我们可以通过以下方式解决它:

// Auto calculate table colspan if set to 0
var colCount = 0;
$("td[colspan='0']").each(function(){
    colCount = 0;
    $(this).parents("table").find('tr').eq(0).children().each(function(){
        if ($(this).attr('colspan')){
            colCount += +$(this).attr('colspan');
        } else {
            colCount++;
        }
    });
$(this).attr("colspan", colCount);
});

http://tinker.io/3d642/4

http://tinker.io/3d642/4

回答by Joshua

td.setAttribute('rowspan',x);

td.setAttribute('rowspan',x);