简体   繁体   English

Opera中html()处理的jQuery问题

[英]JQuery problem with html() handling in Opera

I have following JS code (stripped to minimal size where problem still exists) 我有以下JS代码(在问题仍然存在的情况下缩小到最小大小)

<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 works and <em> tags are replaced with <strong>. 在Firefox中,一切正常,并且<em>标记已替换为<strong>。

But in Opera <em>'s are stay in place. 但是在Opera <em>中仍然存在。 Furthermore, any other HTML tags are not captured by regexps at all. 此外,其他任何HTML标记都不会被正则表达式捕获。

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). 我不仅需要替换标签,还需要解析它们的内容(例如href属性)。

Opera returns tags as uppercase, eg <EM> . Opera以大写形式返回标签​​,例如<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: 当您可以使用DOM方法时,请不要使用字符串方法:

$("#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 您的正则表达式在Opera中不匹配,因为它已将所有HTML标记规范化为大写,并使用// gi

However if you are doing more changes ("parsing their content"), I really would recommend doing proper DOM manipulation and not using regular expressions. 但是,如果您要进行更多更改(“解析其内容”),我真的建议您进行适当的DOM操作,而不要使用正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM