[英]How can I get name from link?
I'm writing on objective-C. 我在写Objective-C。 I have
WebView
and local file index.html has 我有
WebView
,本地文件index.html有
<a href='http://www.google.com' name="666">
How can I get the name
attribute? 如何获得
name
属性?
Thanks! 谢谢!
It depends on when/by what you need to get the name. 这取决于您何时/按什么名称获得。 If you need the name when someone clicks on the link, you can set up some JavaScript that runs when the link is clicked (onclick handler).
如果在有人单击链接时需要名称,则可以设置一些在单击链接时运行的JavaScript(onclick处理程序)。 If you just have the html string, you can use regular expressions to parse the document and pull out all of the name attributes.
如果只有html字符串,则可以使用正则表达式来解析文档并提取所有名称属性。 A good regular expression library for Objective-C is RegexKit (or RegexKitLite on the same page).
RegexKit (或同一页面上的RegexKitLite)是Objective-C的一个很好的正则表达式库。
The regular expression for parsing the name attribute out of a link would look something like this: 用于从链接中解析name属性的正则表达式如下所示:
/<a[^>]+?name="?([^" >]*)"?>/i
EDIT: The javascript for getting a name out of a link when someone clicked it would look something like this: 编辑:当有人单击它时,从链接中获取名称的javascript看起来像这样:
function getNameAttribute(element) {
alert(element.name); //Or do something else with the name, `element.name` contains the value of the name attribute.
}
This would be called from the onclick
handler, something like: 这将从
onclick
处理程序中调用,例如:
<a href="http://www.google.com/" name="anElementName" onclick="getNameAttribute(this)">My Link</a>
If you need to get the name back to your Objective-C code, you could write your onclick function to append the name attribute to the url in the form of a hashtag, and then trap the request and parse it in your UIWebView delegate's -webView:shouldStartLoadWithRequest:navigationType:
method. 如果需要将名称恢复为Objective-C代码,则可以编写onclick函数以将名称属性以
-webView:shouldStartLoadWithRequest:navigationType:
标签的形式附加到url,然后捕获请求并将其解析到UIWebView委托的-webView:shouldStartLoadWithRequest:navigationType:
方法。 That would go something like this: 那会是这样的:
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.