如何从链接获取名称?
问题描述:
我正在编写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