2011-07-01 47 views
0

我正在使用UIWebView。我想要做的是在webview加載的內容中添加一個div。 爲此,我寫的代碼如下:UIWebView stringByEvaluatingJavaScriptFromString問題

NSString *strInputJS = [NSString stringWithFormat:@"var newDiv = document.createElement('div');newDiv.innerHTML = '<h1>Hi there!</h1>';document.body.appendChild(newDiv);newDiv.style.height = 100 + 'px';"]; 

    NSString *strResult = [_webview stringByEvaluatingJavaScriptFromString:strInputJS]; 

但它無法正常工作。我想同樣的JavaScript和HTML頁面如下:

<html> 
    <head> 
    <title>JSTrial</title> 
    </head> 
    <body> 
    <script> 
    var newDiv = document.createElement('div'); 
    newDiv.innerHTML = '<h1>Hi there!</h1>'; 
    document.body.appendChild(newDiv); 
    newDiv.style.height = 100 + 'px'; 
    </script> 
    </body> 
    </html> 

我在Safari瀏覽器中打開HTML頁面,以及在iPhone模擬器的Safari瀏覽器。它運作良好。

網絡視圖已經加載在我試圖注入新的JS的點。 我發現的是,newDiv.style爲null。

這段代碼有什麼問題?

回答

0

注意從未使用變量numberOfPixelsForPadding。

  • 檢查沒有u盤在webViewDidFinishLoad

    委派正確

  • 呼叫stringByEvaluatingJavaScriptFromString - (空)webViewDidFinishLoad:(UIWebView的*)webView的 { 的NSString * strInputJS = [的NSString stringWithFormat:@「VAR newDiv = document.createElement('div'); newDiv.innerHTML ='

    Hi there!

    '; document.body.appendChild(newDiv); newDiv.style.height = 100 +'px';「];

    [webView stringByEvaluatingJavaScriptFromString:strInputJS];

    }

注:

NSString *strInputJS = [NSString stringWithFormat:@"var newDiv = document.createElement('div');newDiv.innerHTML = '<h1>Hi there!</h1>';document.body.appendChild(newDiv);newDiv.style.height = 100 + '%ipx';",numberOfPixelsForPadding]; 

我認爲這將有助於.. !!

+0

嗨Dileep,感謝您的答覆。我試圖消除這個毫不含糊的論點。但問題依然存在。我修改了代碼更改的問題以刪除參數。 –

+0

是你的JavaScript代碼是在webViewDidFinishLoad ..檢查webView.delegate = self; –

+0

webView.delegate設置爲self。我的JavaScript代碼不在webViewDidFinishLoad中,但在加載webView後的某個時間點。但我已經嘗試了webViewDidFinishLoad上的JS,同樣的問題。此外,我的JS正在工作,直到風格被設定爲新Div之前的時間點。但在訪問風格時失敗。樣式爲空。 - 相同的JS在瀏覽器中工作正常。 –