[英]How can I get name from link?
我在寫Objective-C。 我有WebView
,本地文件index.html有
<a href='http://www.google.com' name="666">
如何獲得name
屬性?
謝謝!
這取決於您何時/按什么名稱獲得。 如果在有人單擊鏈接時需要名稱,則可以設置一些在單擊鏈接時運行的JavaScript(onclick處理程序)。 如果只有html字符串,則可以使用正則表達式來解析文檔並提取所有名稱屬性。 RegexKit (或同一頁面上的RegexKitLite)是Objective-C的一個很好的正則表達式庫。
用於從鏈接中解析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函數以將名稱屬性以-webView:shouldStartLoadWithRequest:navigationType:
標簽的形式附加到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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.