字符串的大写首字母在IE 7中崩溃

时间:2011-12-14 09:05:50

标签: javascript jquery internet-explorer-7

actualizarTituloWeb('brand name - '+seccion.toLowerCase().replace(/(?:_| |\b)(\w)/g, function(str, p1) { return p1.toUpperCase()}));

,其中

function actualizarTituloWeb(titulo){
        $( 'title' ).html ( titulo );  
}

还试过:

function actualizarTituloWeb(titulo){

        titulo = titulo[0].toUpperCase() + titulo.substring(1);

            titulo = titulo.toLowerCase();

            $( 'title' ).text ( titulo );

        return false;
}

和seccion的值包括'reserva','ofertas',..

我不确定为什么不能正常工作,但这实际上会导致整个脚本崩溃(可在此处进行测试:http://toniweb.us/gm2)在IE7中并且当前文档的标题既未更新,

任何想法我错过了什么?

- 编辑 -

刚才意识到问题出在这一行!为什么呢?

titulo = titulo[0].toUpperCase() + titulo.substring(1);

请注意:我们不能在这里使用CSS来实现这一点,因为它将用于document.title

3 个答案:

答案 0 :(得分:5)

在JScript< = 5.7(IE 7)中,您无法像数组一样访问字符串。您必须使用String.charAt()。类似于数组的访问在ES 5中标准化。

titulo = titulo.charAt(0).toUpperCase() + titulo.substring(1);

此外$('title').text(titulo);不起作用。在最高版本8的IE中,您无法通过title-element的textContent设置(或获取)标题。

<html>
<head>
    <title>test</title>
</head>
<body>
    <script type='text/javascript'>
document.getElementsByTagName('title')[ 0 ].firstChild // null in IE <= 8
                                                       // IE 9 (and other browser): text node with nodeValue 'test'
    </script>
</body>
</html>

使用document.title

document.title = titulo;

答案 1 :(得分:1)

通过对正则表达式模式稍加修改,可以实现预期的行为

actualizarTituloWeb('brand name - ' + seccion.toLowerCase().replace(/(^|\s|\-)(.)/gi, function(c) { return c.toUpperCase()}));

答案 2 :(得分:0)

你为什么不这样做:

var str = "blah blah";
str = str.toLowerCase();
str = str[0].toUpperCase() + str.substring(1);
document.title = str;