【问题标题】:How can I get name from link?如何从链接中获取名称?
【发布时间】:2011-04-25 06:02:19
【问题描述】:

我在写 Objective-C。 我有WebView 和本地文件 index.html 有

<a href='http://www.google.com' name="666">

如何获得name 属性?

谢谢!

【问题讨论】:

    标签: html objective-c


    【解决方案1】:

    这取决于您何时/通过什么来获取名称。如果您在有人单击链接时需要名称,您可以设置一些在单击链接时运行的 JavaScript(onclick 处理程序)。如果您只有 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 函数以将名称属性以井号标签的形式附加到 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。请你写一些例子好吗?谢谢!
    猜你喜欢
    • 2023-02-22
    • 1970-01-01
    • 2016-09-10
    • 2022-11-04
    • 2013-08-03
    • 2016-04-08
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多