如何从目标C中的stringByEvaluatingJavaScriptFromString:方法执行长javascript?

时间:2015-04-02 03:45:40

标签: javascript ios objective-c uiwebview

我想获取用户在网页输入字段中输入的所有值。我试过这段代码:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

    NSString *javaScript = @"var e = document.getElementsByTagName('input')for(var e in elements){if(e.type == 'text'){e.value}}";
    NSString *html = [myWebView stringByEvaluatingJavaScriptFromString:javaScript];

    NSLog(@"test of html: %@",html);

    return YES;
}

好像它不起作用:

如果我知道id:

javaScript = @"document.getElementById('lst-ib').value";
NSString *html = [myWebView stringByEvaluatingJavaScriptFromString:javaScript];

它会起作用。

1 个答案:

答案 0 :(得分:0)

for (int i = 0; i<100; i++) {

    NSString *javaScript = [NSString stringWithFormat:@"document.getElementsByTagName('input')[%d].value",i];

    NSString *test = [NSString stringWithFormat:@"document.getElementsByTagName('input')[%d].name",i];

    NSString *html = [myWebView stringByEvaluatingJavaScriptFromString:javaScript];

    NSString *html2 = [myWebView stringByEvaluatingJavaScriptFromString:test];

    if (html.length > 2) {
        NSLog(@"Value %d: >>>> %@    %@",i,html,html2);
    }
}

这解决了我的疑问。我没有实现长javascript但是通过目标c循环代码。