使用javascript交换表的td元素

时间:2017-02-12 18:43:49

标签: javascript jquery html

有没有一种使用javascript交换html表元素的简单方法?

例如有一个像这样的表:

<table>
<tr>
    <td class = "draggable">
        <div class = "droppable">Item 1</div>
    </td>
</tr>
<tr>
    <td class = "draggable">
        <div class = "droppable">Item 2</div>
    </td>
</tr>

我想让它可用于交换单元格。 谢谢!

2 个答案:

答案 0 :(得分:0)

你可以像换掉任何变量的内容一样:

import numpy as np
from sklearn import linear_model

data = np.loadtxt('/Users/Nikesh/Downloads/linear_regression_live-master/data.csv', delimiter=',')
regr = linear_model.LinearRegression()
regr.fit(data[:, 0:1], data[:, 1:2])
print 'Co-efficients : ', regr.coef_
print 'Intercept : ', regr.intercept_
print 'Regression line : ',regr.intercept_,'+',regr.coef_,' X'

答案 1 :(得分:0)

我已经写了一个交换元素的小函数。作为参数传递父(交换元素的容器),以及要交换的子元素的两个数字(索引)。

&#13;
&#13;
var rowsParent = document.getElementById('sortRows');
var cellsParent = document.getElementById('sortCells');

swapElements(rowsParent,0,1);
swapElements(cellsParent,2,0);

function swapElements(parent,elemA,elemB){
    //a little of validation
    if(!parent||parent.constructor.toString().search('HTML')===-1) return;
    var children = parent.children;
    if(typeof elemA!=='number' || typeof elemB!=='number' || elemA===elemB || !children[elemA] || !children[elemB]) return;
	
    elemB = elemA<elemB ? elemB--:elemB;
    var childNumb = children.length - 1;
	
    var a = parent.removeChild(children[elemA]);
    var b = parent.removeChild(children[elemB]);
    append(elemB,a);
    append(elemA,b);
	
       function append(a,b){
          childNumb===a ? parent.appendChild(b) : parent.insertBefore(b,children[a]);
       }
}
&#13;
table, td {
  border: solid 1px black;
  padding: 3px;
  margin: 15px;
}
&#13;
<table>
  <tbody id="sortRows">
    <tr>
      <td>a 1</td>
      <td>a 2</td>
      <td>a 3</td>
      <td>a 4</td>
      <td>a 5</td>
    </tr>
    <tr id="sortCells">
      <td>b 1</td>
      <td>b 2</td>
      <td>b 3</td>
      <td>b 4</td>
      <td>b 5</td>
    </tr>
    <tr>
      <td>c 1</td>
      <td>c 2</td>
      <td>c 3</td>
      <td>c 4</td>
      <td>c 5</td>
    </tr>
    <tr>
      <td>d 1</td>
      <td>d 2</td>
      <td>d 3</td>
      <td>d 4</td>
      <td>d 5</td>
    </tr>
    <tr>
      <td>e 1</td>
      <td>e 2</td>
      <td>e 3</td>
      <td>e 4</td>
      <td>e 5</td>
    </tr>    
  </tbody>
</table>
&#13;
&#13;
&#13;