在iOS UIWebView上运行javascript函数

时间:2014-07-31 22:40:54

标签: javascript ios uiwebview

我正在尝试从UIWebView运行javascript。我想运行的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;
    }
}

}

我知道您可以使用

在UIWebView中执行javascript
(NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script

所以我将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;\
        }\
    }\
}";

并运行javascript为

[webView stringByEvaluatingJavaScriptFromString:str];

但这似乎不起作用。有什么我做错了吗?

1 个答案:

答案 0 :(得分:4)

看起来你的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;\
        }\
    }\
}\
selectAnimal();";