自动填写tr的Javascript编辑

时间:2014-05-10 11:26:48

标签: javascript jquery

我从这里得到了这个Javascript ..

这里的JS:

<script>
var tables = document.getElementsByTagName('table');
var table = tables[tables.length - 1];
var rows = table.rows;
for(var i = 0, td; i < rows.length; i++){
    td = document.createElement('td');
    td.appendChild(document.createTextNode(i + 1));
    rows[i].insertBefore(td, rows[i].firstChild);
}
</script>

这会在所有td之前创建一个td

例如,如果我们创建此表:

<table>
<tr>
<td>First TD
</td>
<tr></tr>
<td>Second TD
</td>
</tr>
</table>

这个脚本会像这样创建..

    <table>
<tr>
<td>1
</td>
<td>First TD
</td>
</tr>
<tr>
<td>2
</td>
<td>Second TD
</td>
</tr>
</table>

我想在此之前排除TH部分以创建一个td ..

2 个答案:

答案 0 :(得分:0)

我不确定我是否理解你,但你想做的事情就像我在这个jsFiddle中所做的那样:
http://jsfiddle.net/YbM97/3/

我修改了for-循环并在第一个1之前做一个TH元素。

EDITED:
为第几个元素添加了“not-sortable”类。
使用Javascript:

var tables = document.getElementsByTagName('table');
var table = tables[tables.length - 1];
var rows = table.rows;

var th = document.createElement('th');
th.className = "not-sortable";
th.appendChild(document.createTextNode("ID"));
rows[0].insertBefore(th, rows[0].firstChild);

for(var i = 1, td; i < rows.length+1; i++){
    var td = document.createElement('td');
    td.appendChild(document.createTextNode(i));
    rows[i].insertBefore(td, rows[i].firstChild);
}

HTML:

<table>
    <tr>
        <th class="not-sortable">Name</th>
    </tr>
    <tr>
        <td>First TD</td>
    </tr>
    <tr>
        <td>Second TD</td>
    </tr>
</table>

答案 1 :(得分:0)

虽然你已经接受了问题的答案,但我还有几分钟时间,并认为我会提供替代方法;第一个解决了您希望清楚地枚举表格的行添加相关标题(或简单地跳过标题)和样式的愿望。第二个,使用CSS,只是枚举行。

首先,JavaScript:

function enumerateTable(opts) {
    // setting default options:
    var s = {
        // finding the first 'table' element on the page:
        'table': document.getElementsByTagName('table')[0],
            // do we add a 'thead' (true) or not (false)
            'addHeader': true,
            // array of column headings:
            'colHeader': ['number', 'name'],
            // index to start counting from:
            'countFrom': 1,
            // classname of created 'th' elements:
            'thClass': '',
            // classname of created 'td' elements:
            'tdClass': 'index',
            // do we add increased colspan to the first column
            // (true) or the last column (false):
            'padLeft': false
    },
    // 'empty' variable for later use:
    optType;

    // iterating over the options supplied by the user,
    // updating the defaults we defined earlier:    
    for (var prop in opts) {
        // if the property exists in the object (not the prototype):
        if (opts.hasOwnProperty(prop)) {
            // storing the specific property-value in the declared variable:
            optType = typeof opts[prop];

            // if the property is undefined, or
            // the property is a string *and* has a length of zero (an
            // empty string) we use the default, otherwise we use the
            // user-supplied option/setting:
            s[prop] = 'undefined' === optType || ('string' === optType && opts[prop].length === 0) ? s[prop] : opts[prop];
        }
    }

    // if the user supplied a string for the table property, we assume
    // it's the id of the table element; otherwise we assume it's a
    // HTMLTableElement/DOM-node and use that:
    s.table = 'string' === typeof s.table ? document.getElementById(s.table) : s.table;

    // all browsers (that I've ever experimented with) wrap the table's 'tr' elements
    // together in a 'tbody' element, so we assume the contents to enumerate are
    // contained within; here we retrieve the first of those 'tbody' elements:
    var tableBody = s.table.getElementsByTagName('tbody')[0],
        // get the 'tr' elements from the 'tbody':
        rows = tableBody.getElementsByTagName('tr'),
        // create an empty 'td' element (for later use):
        cell = document.createElement('td'),
        // look to see if 'textContent' is a property of the document.body,
        // if it is we use that as the 'textProperty', otherwise we use 'innerText':
        textProperty = 'textContent' in document.body ? 'textContent' : 'innerText',
        // empty variable for later use:
        newCell;

    // setting the classname of the newly-created 'td' element:    
    cell.className = s.tdClass;

    // iterating over the rows:
    for (var i = 0, len = rows.length; i < len; i++) {
        // cloning the created 'td' element:
        newCell = cell.cloneNode();

        // setting its text equal to the starting index + the iterator index:
        newCell[textProperty] = s.countFrom + i;

        // inserting the newCell variable into the current row before its first child:
        rows[i].insertBefore(newCell, rows[i].firstChild);
    }

    // if we want to add a header, *and* we have column headings *and* that
    // array/string isn't empty:
    if (s.addHeader === true && s.colHeader && s.colHeader.length) {
        // creating a 'thead' element:
        var thead = document.createElement('thead'),
            // creating a 'tr' element:
            row = document.createElement('tr'),
            // creating a 'th' element:
            th = document.createElement('th'),
            // the number of (element) children of the first 'tr':
            length = rows[0].children.length,
            // how many column-headings do we have:
            headLength = s.colHeader.length,
            // the difference between the number of children and the
            // number of headings:
            delta = length - headLength,
            // empty variable for later use:
            thClone;

        th.className = s.thClass;

        // iterating over the column-headings:    
        for (var i = 0; i < headLength; i++) {
            // cloning the created 'th' element:
            thClone = th.cloneNode();
            // setting its text to the heading held at the current point in the array:
            thClone[textProperty] = s.colHeader[i];

            // if this is the last heading and we're not padding the left cells
            if (i === headLength - 1 && s.padLeft === false) {
                // setting the colspan:
                thClone.setAttribute('colspan', 1 + delta);
            // otherwise, if this is the first heading, and we're 'padding' from the
            // left:
            } else if (i === 0 && s.padLeft === true) {
                thClone.setAttribute('colspan', 1 + delta);
            }

            // appending the modified clone to the 'thead':
            thead.appendChild(thClone);
        }

        // appending the thead before the first child of the 'table' element:
        s.table.insertBefore(thead, s.table.firstChild);
    }

    // returning the modified table (for chaining purposes):
    return s.table;
}


enumerateTable({
    // DOM/HTMLTableElement, or String (the id of the table):
    'table': 'myTable',
    // Boolean; true (we add a 'thead' element) or false (we don't):
        'addHeader': true,
    // Array of headings for the table:
        'colHeader': ['number','name'],
    // Number: the number to start counting from:
        'countFrom' : 1,
    // String: the class-name to apply to the created 'th' elements:
        'thClass': 'not-sortable',
    // String: the class-name to apply to the created 'td' elements:
        'tdClass': 'index',
    // Boolean: true (we apply colspan to the first 'th'),
    // false (we apply colspan to the last 'th'):
        'padLeft': true
});

JS Fiddle demo

通过传递DOM节点/ HTMLTableElement(而不是上面的字符串),设置单个列标题,设置创建的th元素的类名,以及使用不同的元素来演示如何使用该函数计数的起始指数。

此外,这演示了如何从函数链接,将color元素的table设置为'silver':

enumerateTable({
    'table': document.getElementById('myTable'),
    'colHeader': ['name'],
    'thClass' : 'not-sortable',
    'countFrom' : 10
}).style.color = 'silver';

JS Fiddle demo

另一种方法,使用CSS枚举table元素的(预先存在的)内容;使用HTML:

<table>
    <thead>
        <tr>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>First TD</td>
        </tr>
        <tr>
            <td>Second TD</td>
        </tr>
    </tbody>
</table>

<table id="myTable">
    <tbody>
        <tr>
            <td>First TD</td>
        </tr>
        <tr>
            <td>Second TD</td>
        </tr>
    </tbody>
</table>

CSS:

// incrementing the rowNumber counter (doesn't require initialising before use):
tbody tr {
    counter-increment: rowNumber;
}

// creating pseudo-element before the first td of each row of the tbody:    
tbody tr td:first-child::before {
    // the content is the counter itself:
    content: counter(rowNumber);
    // to allow for defined width/padding:
    display: inline-block;
    width: 1em;
    padding-right: 0.5em;
    margin-right: 0.5em;
}

JS Fiddle demo

参考文献: