是否可以将HTML表的一列作为单个HTML元素进行访问?

时间:2014-02-27 19:14:02

标签: javascript html range

出于对我的应用程序目的非常重要的目的,我在UIWebView中的HTML表格中显示文本内容。以下是该设置的示例:

<table width = "100%">
     <tbody>
          <tr>//Row 1
               <td>
                    Here is the text of the first row of the table, first cell in the row
               </td>
               <td>
                    Here is the text of the first row of the table, second cell in the row
               </td>
          </tr>
          <tr>//Row 2
               <td>
                    Here is the text of the second row of the table, first cell in the row
               </td>
               <td>
                    Here is the text of the second row of the table, second cell in the row
               </td>
          </tr>
     </tbody>
</table>

如果我选择其中一行中的某些文本,则获取父元素并不是很难,并且获取该选择的范围相对于该行中整个句子的范围。因此,例如,如果我选择第二行的文本“Here”,则该文本相对于该行的范围是0-3。

我想知道是否可以组合表的行(以列为基础),以便元素的长度不仅仅是我选择的行中的句子,还包括所有其他行。 / p>

换句话说,我需要相对于表格中的所有行获取所选文本范围(开始,结束),而不仅仅是所选文本的行。

例如,如果我们保持选择相同的单词,但在整个表的内容的上下文中查看它,范围将不再是0-3,它将是59-63,因为我们是还包括它上面的行和它的内容。有效地将整个列视为HTML元素。

这可能吗?

1 个答案:

答案 0 :(得分:1)

您可以使用jQuery将所有调用串在一起的能力

 $('tr td:first-of-type').text()

http://jsfiddle.net/gNvnp/1/

没有jQuery(在现代浏览器中)

// no jquery
var combineCols = function(selector) {
  var cols = document.querySelectorAll(selector);
  var len = cols.length;
  var str = '';
  while (len--) {
     str = cols[len].innerText + ' ' + str;   
  }
  return str;
}

http://jsfiddle.net/gNvnp/3/