如何使用html文件调用js文件

时间:2014-04-16 08:54:16

标签: ios uiwebview

我可以将js文件注入html文件吗? 我试过Loading javascript into a UIWebView from resources但我无法加载js文件

lib.js

function alertMeWithMyCustomFunction(text) {
    alert(text+' -> in lib.js');
}

的test.html

<!DOCTYPE html>
<html>
    <head>
        <title>MathJax</title>
        <script type=\"text/javascript\" src=\"lib.js\" />
        <script type=\"text/javascript\" src=\"MathJaxUnpacked/MathJax.js\"></script>
        <script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [[\"$\",\"$\"],[\"\\(\",\"\\)\"]]}});</script>
    </head>
    <body>
        <br>
        <a href=\"javascript:alertMeWithMyCustomFunction('I am');\">External js test</a>
        <br>
        <br>
        <a href=\"javascript:alert('Works!')\">Test Javascript Alert</a>


        <br>
            <h1>MathJax Test</h1>
        <br>
        <p>Here the HTML is dynamically inserted using loadHTMLString in a UIWebView, and the JavaScript and image are referenced from the resources of the application.</p>
        <br>
        <p>$$\\int_x^y f(x) dx$$</p>
        <br>
        <br>
        <img src=\"images/test.jpg\">
    </body>
</html>

viewdidload中的代码

NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"Test" ofType:@"html"];
    NSString *html = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
    _webview = [[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
 [_webview loadHTMLString:html
                    baseURL:[NSURL fileURLWithPath:
                             [[NSBundle mainBundle] bundlePath]]];


    [self setView: _webview];

我做错了什么?我没有文件夹结构,文件在项目默认文件夹结构中自己。 enter image description here当我点击链接时没有任何事情发生

1 个答案:

答案 0 :(得分:0)

heck UIWebView方法叫做:

stringByEvaluatingJavaScriptFromString:(NSString *)script;

NSString *result = [_webView stringByEvaluatingJavaScriptFromString:(@"alert('test')