2014-03-27 55 views
0

有人請幫助我,我如何獲取加載的UIWebView頁面中的所有textFields值(與其「名稱」「ID」) 。在目標C中訪問WebView元素

或請提供其描述所有的jQuery字符串在

   "stringByEvaluatingJavaScriptFromString" 

方法作爲參數來傳遞的鏈接。

回答

1

下面是JavaScript代碼,你應該使用:

(function(){ 
    var i, tf, textFields = document.getElementsByTagName("input"), result = []; 
    for (i = 0; tf = textFields[i]; i++) { 
     if (tf.type === "text" || tf.type === "search") 
      result.push({ 
       "type": tf.type, 
       "name": tf.name, 
       "id": tf.id, 
       "value": tf.value 
      }); 
    } 
    return JSON.stringify(result); 
})(); 

你可能會發現你要添加額外的輸入字段類型。

這裏是一個Objective-C的代碼示例:

- (void)getValuesButtonTapped:(id)sender { 
    NSString *resultStr = [self.webView stringByEvaluatingJavaScriptFromString: 
     @"(function(){" 
      "var i, tf, textFields = document.getElementsByTagName(\"input\"), result = [];" 
      "for (i = 0; tf = textFields[i]; i++) {" 
       "if (tf.type === \"text\" || tf.type === \"search\")" 
        "result.push({\"type\": tf.type, \"name\": tf.name, \"id\": tf.id, \"value\": tf.value});" 
      "}" 
      "return JSON.stringify(result);" 
     "})();" 
    ]; 
    NSArray *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; 
    NSLog(@"result: %@", result); 
} 

enter image description here

當您點擊 「獲取值...」 按鈕,您會收到以下日誌消息:

result: ({ 
    id = "lst-ib"; 
    name = q; 
    type = search; 
    value = "hello world"; 
}, 
    { 
    id = ""; 
    name = ""; 
    type = text; 
    value = ""; 
}, 
    { 
    id = ""; 
    name = ""; 
    type = text; 
    value = ""; 
}) 
+0

如何獲得密碼字段中的文本? –

+0

密碼字段是「密碼」類型的「」,因此您可以添加「||」。在上面的例子中,tf.type ===「password」到上面例子中的if語句返回密碼字段值 – smnh

+0

如何獲取請給出代碼如果可能的話。 –