【问题标题】:Javascript not executing in iPhoneJavascript 未在 iPhone 中执行
【发布时间】:2011-07-04 05:36:23
【问题描述】:

我想使用 UIWebView 从我的 iPhone 应用程序中执行 javascript 代码。

但是只有 html 部分正在执行,而 javascript 部分没有执行。它也没有显示错误。

NSMutableString *htmlCode = [NSMutableString stringWithString:@"<!DOCTYPE HTML>"];


[htmlCode appendString:@"<html><head><tilte> sadaf </title>"];

[htmlCode appendString:@"<h1>My First Web Page</h1>"];


[ htmlCode appendString:@" <p id='demo'>This is a paragraph.</p>"];
[self.webView loadHTMLString:htmlCode baseURL:nil];


webView.delegate= self;

[webView stringByEvaluatingJavaScriptFromString:@"<script type='text/javascript'>document.getElementById('demo').innerHTML=Date();</script>   "];

【问题讨论】:

    标签: javascript iphone


    【解决方案1】:

    如果您使用stringByEvaluatingJavaScriptFromString 来评估您的JavaScript,那么您不需要将您的JavaScript 代码包装在&lt;script&gt; 标记中(事实上,这样做会阻止您的脚本执行)。试试这个:

    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('demo').innerHTML=Date();"];
    

    【讨论】:

    • @mplungjan - 是的,我应该更清楚。如果您在传递给stringByEvaluatingJavaScriptFromString 的字符串中使用&lt;script&gt; 标记,那么您的JavaScript 将不会被评估。
    • @aroth - 然后我在哪里写这段代码
    【解决方案2】:

    检查委托是否设置正确。

    - (void)viewDidLoad 
    {
        [super viewDidLoad];
    
        //  init and create the UIWebView
        webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 88, 320, 400)]; 
        webView.autoresizesSubviews = YES;
        webView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
        [webView  setDelegate:self];//set the web view delegates for the web view to be itself
        NSMutableString *htmlCode = [NSMutableString stringWithString:@"<!DOCTYPE HTML>"];
    
        [htmlCode appendString:@"<h1>My First Web Page</h1>"]; 
        [htmlCode appendString:@" <p id='demo'>This is a paragraph.</p>"]; 
        [htmlCode appendString:@"</form> </body> </html> "]; 
        [self.webView loadHTMLString:htmlCode baseURL:nil];
    
        [self.view addSubview:webView];//add the web view to the content view
    }
    
    - (void) webViewDidFinishLoad:(UIWebView *)webView1
    {
        NSLog(@"webViewDidFinishLoad");
        [webView1 stringByEvaluatingJavaScriptFromString:@"alert('hi');document.getElementById('demo').innerHTML=Date();"];
    }
    

    这可能会有所帮助!

    【讨论】:

      猜你喜欢
      • 2018-05-03
      • 1970-01-01
      • 2017-02-13
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多