0
我正在編寫Objective-C。 我有WebView
和地方index.html文件有如何從鏈接獲取名稱?
<a href='http://www.google.com' name="666">
我怎樣才能獲得name
屬性?
謝謝!
我正在編寫Objective-C。 我有WebView
和地方index.html文件有如何從鏈接獲取名稱?
<a href='http://www.google.com' name="666">
我怎樣才能獲得name
屬性?
謝謝!
這取決於何時/通過你需要什麼名字。如果某人點擊該鏈接時需要該名稱,則可以設置一些在單擊該鏈接時運行的JavaScript(onclick handler)。如果您只有html字符串,則可以使用正則表達式來解析文檔並提取所有名稱屬性。 Objective-C的一個好的正則表達式庫是RegexKit(或同一頁上的RegexKitLite)。
解析name屬性進行鏈接會是這個樣子的正則表達式:
/<a[^>]+?name="?([^" >]*)"?>/i
編輯:爲得到一個名字出來一個鏈接,當有人點擊它看起來會是JavaScript的像這樣:
function getNameAttribute(element) {
alert(element.name); //Or do something else with the name, `element.name` contains the value of the name attribute.
}
這被稱爲從onclick
處理程序是這樣的:
<a href="http://www.google.com/" name="anElementName" onclick="getNameAttribute(this)">My Link</a>
如果您需要將名稱恢復爲您的Objective-C代碼,您可以編寫onclick函數以hashtag形式將name屬性附加到url,然後捕獲請求並將其解析爲您的UIWebView代理的-webView:shouldStartLoadWithRequest:navigationType:
方法。這將是這樣的:
function getNameAttribute(element) {
element.href += '#'+element.name;
}
//Then in your delegate's .m file
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
NSArray *urlParts = [[request URL] componentsSeparatedByString:@"#"];
NSString *url = [urlParts objectAtIndex:0];
NSString *name = [urlParts lastObject];
if([url isEqualToString:@"http://www.google.com/"]){
//Do something with `name`
}
return FALSE; //Or TRUE if you want to follow the link
}
我需要的名字,當有人點擊鏈接。但我不知道如何使用JavaScript。你能寫一些例子嗎?謝謝! – Sveta 2011-04-25 06:22:34
查看我更新的答案。 – Kyle 2011-04-25 18:36:59