开发者

JQuery problem with html() handling in Opera

开发者 https://www.devze.com 2022-12-13 06:08 出处:网络
I have following JS code (stripped to minimal size where problem still exists) <html> <head>

I have following JS code (stripped to minimal size where problem still exists)

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="debug">this is <em>test</em></div>
<script type="text/javascript">
    var string1 = $('#debug').html();
    var string2 = string1.replace(/<em>/g, '<strong>');
    string2 = string2.replace(/<\/em>/g, '</strong>');
    $('#debug').html( string2 );
</script>
</body>
</html>

In Firefox everything w开发者_运维知识库orks and <em> tags are replaced with <strong>.

But in Opera <em>'s are stay in place. Furthermore, any other HTML tags are not captured by regexps at all.

Is there any way to fix this behaviour? I need not only to replace tags, but to parse their content too (href attributes for example).


Opera returns tags as uppercase, e.g. <EM>. You need to change your regular expressions to work case-insensitively:

var string2 = string1.replace(/<em>/gi, '<strong>');
string2 = string2.replace(/<\/em>/gi, '</strong>');


Don’t use string methods when you can use DOM methods:

$("#debug em").each(function() {
    var newElem = document.createElement("strong");
    for (int i=0; i<this.childNodes.length; ++i) {
        newElem.appendChild(this.childNodes[i]);
    }
    this.parentNode.replaceNode(newElem, this);
});


Your regular expressions aren't matching in Opera as it has normalised all HTML tags to uppercase try with //gi

However if you are doing more changes ("parsing their content"), I really would recommend doing proper DOM manipulation and not using regular expressions.

0

精彩评论

暂无评论...
验证码 换一张
取 消