js 中的alert title 在 iOS 中如何消失

在iOS app 中经常会嵌套html 代码, 然后  js 的alert 的title 怎么修改呢,不修改的话很丑陋,用户无法接受。如下:


 但是现在有了好的办法就是用 iOS native 的uiwebview 的扩展方法来监听 js的alert 然后自定义 alert 的title ,如下:



这样就可以自定义, 也比较好看了。

方法是 在 你加在webview 的 m 方法中加入:

@interface UIWebView (JavaScriptAlert)

- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame;

@end

@implementation UIWebView (JavaScriptAlert)

- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
    
    
    UIAlertView* customAlert = [[UIAlertView alloc] initWithTitle:@"我是JS Alert"
                                                          message:message
                                                         delegate:nil
                                                cancelButtonTitle:@"确定"
                                                otherButtonTitles:nil];
    
    [customAlert show];
    [customAlert release];
    
}
@end

这样就ok了! 哈哈!

html 代码 :

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  <title>Webview document</title>
    <script type="text/javascript">
        function change_header()
        {
            alert("不错的一天");
        }
     </script>
</head>

<body style="background-color:transparent; color:white;">
    <h4>UIWebView HTML document</h4>
    <button οnclick="change_header()">按钮</button>
</body>

</html>



在JavaScript,如果你不想意外地触发 `alert` 或其他类似的行为(如 `prompt` 或 `confirm`),你需要确保在字符串字面量,当你需要使用这些控制台输出语句的语法时,不被解析成实际的函数调用。以下是一些方法: 1. **使用单引号(')包围字符串**:对于包含特殊字符的字符串,你可以使用单引号,这样 JavaScript 就不尝试解析其的 `alert` 之类的函数名。 ```javascript let message = 'alert("这是一个字符串")'; ``` 2. **转义特殊字符**:如果你确实需要在字符串使用 `alert` 字符,可以使用反斜杠 `\` 进行转义,使其保持原始形式。 ```javascript let message = "alert\\('这是另一个字符串')"; ``` 3. **只在需要的地方使用**:如果你知道某个变量只用于字符串构建,而非实际调用函数,那么只在那个特定部分使用 `alert` 是可行的。 ```javascript const doNotCallAlert = true; if (doNotCallAlert) { let alertMessage = "This will not trigger an alert."; } else { alert(alertMessage); // 只有当 doNotCallAlert 为 false 时才触发 alert } ``` 4. **使用模板字符串 (`template literals`)**:这是一种现代的JavaScript书写方式,它可以更好地处理字符串,包括特殊字符,不被误解为函数调用。 ```javascript let message = `${"alert("}这是一个字符串${")"}`; ``` 记住,在大部分情况下,除非明确需要用户交互,否则最好避免在脚本滥用 `alert`,因为它打断用户的正常浏览体验。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值