在iOS的UIWebView上运行javascript函数

Run javascript function on iOS UIWebView

本文关键字:运行 javascript 函数 UIWebView iOS      更新时间:2023-09-26

我正在尝试从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];

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

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