简体   繁体   English

在iOS UIWebView上运行javascript函数

[英]Run javascript function on iOS UIWebView

I am trying to run a javascript from a UIWebView. 我正在尝试从UIWebView运行javascript。 The javascript function I want to run is the one below 我要运行的javascript函数如下

function SelectAnimal() {
var sel = document.getElementById('Animals');
var val = document.getElementById('AnimalToFind').value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
    if(sel.options[i].innerHTML === val) {
       sel.selectedIndex = i;
       break;
    }
}

} }

I know you can execute javascript in UIWebView using 我知道你可以使用UIWebView中执行javascript

(NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script

So i form the javascript string as 所以我形成的JavaScript字符串为

NSString *str = @"function SelectAnimal() {\
    var sel = document.getElementById('Animals');\
    var val = document.getElementById('AnimalToFind').value;\
    for(var i = 0, j = sel.options.length; i < j; ++i) {\
        if(sel.options[i].innerHTML === val) {\
            sel.selectedIndex = i;\
            break;\
        }\
    }\
}";

and run the javascript as 并以

[webView stringByEvaluatingJavaScriptFromString:str];

But this doesnt seem to work. 但这似乎不起作用。 Is there something i'm doing wrong? 我做错什么了吗?

Looks like your javascript is only defining the function, but never calling it. 看起来您的JavaScript只是在定义函数,而从未调用它。

Try changing to: 尝试更改为:

NSString *str = @"function SelectAnimal() {\
    var sel = document.getElementById('Animals');\
    var val = document.getElementById('AnimalToFind').value;\
    for(var i = 0, j = sel.options.length; i < j; ++i) {\
        if(sel.options[i].innerHTML === val) {\
            sel.selectedIndex = i;\
            break;\
        }\
    }\
}\
selectAnimal();";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM