1

我想在 UIWebView 中获取选定的单词。但有时我无法得到。这是我的代码。

我使用 javascript 来获取选定的单词。(getSelectedword.js)

var selectedText = "";
function getTextSelection() {
   var text = window.getSelection();
   selectedText = text.anchorNode.textContent.substr(text.anchorOffset, text.focusOffset - text.anchorOffset);

 }

接着

-(void)showHeightlight
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"getSelectedword" ofType:@"js"];
NSError *error = nil;
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
[webView stringByEvaluatingJavaScriptFromString:jsCode];
[webView stringByEvaluatingJavaScriptFromString:@"getTextSelection()"];
NSString *result  = [webView stringByEvaluatingJavaScriptFromString:@"selectedText"];
NSLog(@"selected: %@", result);

}

如果我选择了单词并更改了范围,我无法获得选定的单词。

4

1 回答 1

1

我就这样改变我的核心。没关系。

getSelectedword.js

function getTextSelection() {
var text = window.getSelection();
return text.toString();
}

接着

-(void)showHeightlight
{
 NSString *path = [[NSBundle mainBundle] pathForResource:@"getSelectedword" ofType:@"js"];
 NSError *error = nil;
 NSString *jsCode = [NSString stringWithContentsOfFile:path    encoding:NSUTF8StringEncoding error:&error];
 [webView stringByEvaluatingJavaScriptFromString:jsCode];
 NSString *result  = [webView stringByEvaluatingJavaScriptFromString:@"getTextSelection()"];
 NSLog(@"selected: %@", result);
}
于 2011-12-12T02:47:57.853 回答