如何在UIWebView中编辑HTML?

时间:2015-08-19 15:42:16

标签: ios swift uiwebview swift2

我有一个加载HTML的UIWebView。如何访问这些HTML元素并进行更改?

我想做点什么:webView.getHTMLElement(id: main-title).value = "New title"

3 个答案:

答案 0 :(得分:6)

如果您想在表单中编辑它,您可以这样做:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
   NSString *evaluate = [NSString stringWithFormat:@"document.form1.main-title.value='%@';", @"New title"];
   [webView stringByEvaluatingJavaScriptFromString:evaluate];
}

如果不是表格,也许这是(未经测试):

- (void)webViewDidFinishLoad:(UIWebView *)webView {
   NSString *evaluate = [NSString stringWithFormat:@"document.getElementById('main-title').value='%@';", @"New title"];
   [webView stringByEvaluatingJavaScriptFromString:evaluate];
}

请注意!我认为这是一个你想要改变的可编辑字段。否则你在谈论解析,这个概念的工作原理如下:

    static BOOL firstLoad = YES;

    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        if (firstLoad) {
            firstLoad = NO;
            NSString *html = [_webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];
            //Edit html here, by parsing or similar.
            [webView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
        }
    }

您可以在此处阅读有关解析的更多信息:Objective-C html parser

答案 1 :(得分:1)

首先看一下这篇文章 - > Getting the HTML source code of a loaded UIWebView

然后检查一下 - > Xcode UIWebView local HTML

希望这对你有用

答案 2 :(得分:1)

试试这个:

closestAbove = 0 #Defining a variable for the closest larger prime
for curr_odd in odd_list: 
    for curr_prime in prime_list: #Testing each prime for each odd number
        if (closestAbove == 0) or (curr_prime > curr_odd and curr_prime < closestAbove):
            closestAbove = curr_prime
            #This test says if the number is more than the odd number
            #and less than the number we had saved before, we want it
    print(str(curr_odd) + " : " + str(closestAbove))
    closestAbove = 0 #Reset

确保在加载文档后执行此代码。