2013-04-17 19 views
0

有没有一种方法可以在_mouseStop之后使用jquery在表中选择文本?从Jquery中的表中获取选定的文本

<table id='grid' class='TableStyle'> 

    <tr> 
     <td class='cellGrid'>F</td>                  
     <td class='cellGrid'>W</td> 
    </tr> 

    <tr> 
     <td class='cellGrid'>F</td>                  
     <td class='cellGrid'>W</td> 
    </tr> 

</table> 

文本时所强调的,类td的,改为cellHighlight

我认为我需要在表格中循环并找到那些他们的类是cellHighlight,然后使用.text()来获取值?

我对不对?如果是的话,有没有办法做到这一点?

感谢

+0

你只需要一个单击的单元格的文本或多个单元格哪些突出显示?你到底想做什么? –

回答

1
var txt = $("#grid .cellHighlight").text() 
+0

没有工作......他可以选择多个td – Mark

0

如果你想一切都到任何地方得到selectedText您的网页上。你应该做这个。

function getSelectionText() { 
    var text = ""; 
    if (window.getSelection) { 
     text = window.getSelection().toString(); 
    } else if (document.selection && document.selection.type != "Control") { 
     text = document.selection.createRange().text; 
    } 
    alert(text); 
} 

看到这个fiddle

2

如果只有一个(1),可以在同一时间内突出,那么你可以做

var hightlightedText = $('table#grid td.cellHighlight').text(); 
console.log(hightlightedText); 

不过,如果你有多个案例:

var cells = $('#grid .cellHighlight'); 
var texts = [] 
$.each(cells, function(index){ 
    texts.push($(cells[index]).text()); 
}); 
console.log(texts); 
>> ["W", "F"] 

An example JsFiddle found here

0

我发现一些有趣的事情,你想要的东西,可能是这样的:

function getSelectionHtml() { 
    var html = ""; 
    if (typeof window.getSelection != "undefined") { 
     var sel = window.getSelection(); 
     if (sel.rangeCount) { 
      var container = document.createElement("div"); 
      for (var i = 0, len = sel.rangeCount; i < len; ++i) { 
       container.appendChild(sel.getRangeAt(i).cloneContents()); 
      } 
      html = container.innerHTML; 
     } 
    } else if (typeof document.selection != "undefined") { 
     if (document.selection.type == "Text") { 
      html = document.selection.createRange().htmlText; 
     } 
    } 
    alert(html); 
} 

这是由艾莉森回答了这个帖子上How to get selected(user-highlighted) text in contenteditable element and replace it?

0
$("#grid .cellGrid").mouseup(function(){  
    alert($(this).html()); 
}); 
相关问题