【发布时间】:2014-11-12 11:21:41
【问题描述】:
我有一个简单的 HTML 页面,我希望文本区域内的选定文本将其用于某些处理。我已经编写了 jQuery 代码,但我总是得到空字符串作为选择。请帮助我在我的代码中解决此问题。
HTML代码如下:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
</head>
<body>
<form action="#" id="formfirst">
<textarea name="tafirst" rows="10" id="tafirst">Along came Polly ---- Reality Bites ---- Duplex ---- Walter Mitty </textarea>
<br>
<input type="text" id="txtfirst">
<br>
<input type="submit">
</form>
</body>
<script type="text/javascript" src="js/verify.js"></script>
</html>
Javascript 代码如下:(verify.js)
function getSelectedText(){
var t = '';
if(window.getSelection){
t = window.getSelection();
}else if(document.getSelection){
t = document.getSelection();
}else if(document.selection){
t = document.selection.createRange().text;
}
return t;
}
$(document).ready(function(){
//alert("HERE 1");
});
$(document).keypress(function(e){
if($('#tafirst').is(':focus')){
if(e.altKey && e.which==97){
alert(getSelectedText());
e.preventDefault();
}
}
});
编辑
我已经下载了 rangy 插件并将它放在我的 js 文件夹中。我已将该插件包含在我的 HTML 中,如下所示:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="js/rangy/rangy-1.2.3/rangy-core.js"></script>
</head>
<body>
<form action="#" id="formfirst">
<textarea name="tafirst" rows="10" id="tafirst">Along came Polly ---- Reality Bites ---- Duplex ---- Walter Mitty </textarea>
<br>
<input type="text" id="txtfirst">
<br>
<input type="submit">
</form>
</body>
<script type="text/javascript" src="js/verify.js"></script>
</html>
对应修改后的js文件如下:
var range = rangy.createRange();
$(document).ready(function(){
alert(range);
alert("HERE 1");
});
$(document).keypress(function(e){
if($('#tafirst').is(':focus')){
if(e.altKey && e.which==97){
alert(getSelectedText());
e.preventDefault();
}
}
});
但它甚至没有显示任何警报消息。添加rangy的js引用是不是我做错了什么?
【问题讨论】:
-
尝试使用 Tim Down 的 Rangy 插件。获取所选文本是跨浏览器的噩梦。
-
@RoryMcCrossan:编辑代码以使用 rangy 插件。它不工作。请帮助我更正我的代码。
-
获取所选文本非常简单,尽管在问题 (
getSelectedText) 中执行此操作的代码不正确,因为它返回Selection对象而不是大多数浏览器中的字符串。 Here is some better code。无论如何,Rangy 使用相同的基本方法。
标签: javascript jquery rangy