javascript UIWebView iOS document.getElementByID 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6913461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:18:44  来源:igfitidea点击:

UIWebView iOS document.getElementByID does not work

javascriptiphoneobjective-cuiwebview

提问by vodkhang

I am having a really weird bug for UIWebView, I load a very simple html into the UIWebView:

我有一个非常奇怪的错误UIWebView,我将一个非常简单的 html 加载到UIWebView

[self.webview loadHTMLString:@"<html><body><div id='hello'>hello world</div></body></html>" baseURL:nil];

[self.webview loadHTMLString:@"<html><body><div id='hello'>hello world</div></body></html>" baseURL:nil];

and then call 4 lines below:

然后调用下面的 4 行:

NSString *body = [self.webview stringByEvaluatingJavaScriptFromString:
                    @"document.getElementsByTagName('body')[0].outerHTML"];

NSString *helloValue = [self.webview stringByEvaluatingJavaScriptFromString:
                    @"document.getElementByID('hello').value"];

NSString *helloOuter = [self.webview stringByEvaluatingJavaScriptFromString:
          @"document.getElementByID('hello').outerHTML"];

NSString *helloInner = [self.webview stringByEvaluatingJavaScriptFromString:
                @"document.getElementByID('hello').innerHTML"];

NSString *helloElement = [self.webview stringByEvaluatingJavaScriptFromString:
          @"document.getElementByID('hello')"];

Only the first line, using getElementsByTagName return me the correct body html, all other lines just return me an empty string @"". What can go wrong with my code? How can I get the divthat has an id of hello

只有第一行,使用 getElementsByTagName 返回正确的正文 html,所有其他行只返回一个空字符串 @""。我的代码会出现什么问题?我怎样才能得到div具有 id 的hello

回答by vodkhang

I figured out the problem: it was my stupid misspelling, getElementByIdinstead of getElementByID

我发现了问题:这是我愚蠢的拼写错误,getElementById而不是getElementByID