开发者

Regex behaving differently in IE6/IE7

My HTML is something like this :

<select>
    <option>ABC (123)</option>
    <option>XYZ (789)</option>
</select>

What I'm trying to do is: using JQuery and a regex, I replace the "(" with <span>( here's my JQuery line:

$(this).html($(this).html().replace(/\(/g,"<span>("))开发者_如何学JAVA;

It's working as intended in Firefox, chrome and safari, but (as usual) not behaving correctly on IE6/IE7 (the text after "(" just get removed)

Any thoughts ?

PS: I'm doing it this way because I need "(number") to be in a different color, and <span> in a <option> is not valid.


I don't think it's the regex breaking. The below works fine in IE7:

alert("(test".replace(/\(/g,"<span>("));

What's probably happening is that IE6/7 have no clue how to render a span inside an option and just fails to display anything.


You're saying that span in an option is not valid, and yet that's exactly what you're trying to add. Invalid code isn't prettier just because it happens to be valid at load-time, if you know you're going to mess it upp later. So really, if that's your only concern, do add this span declaratively in your HTML, rather than injecting it later.

But if you want to fix this, I think it might help if you rewrite the regex to cover the entire tag. In a lot of cases, IE doesn't let you just change the HTML to whatever, but will use its own internal representation to fix up the code, according to its own preferences. When you write a table, for instance, IE will always internally infer a tbody, even if there isn't any in the code. In the same manner, if you inject a <span> and there's no </span>, IE might insert one by itself. To get around this, make sure you inject the code in its entirety in one go:

$(this).html($(this).html().replace(/\((.*?)\)/g,"<span>($1)</span>"));


I don't have IE7 but in IE6 the following

javascript:"<select><option>ABC (123)</option><option>XYZ (789)</option></select>".replace(/\(/g,"<strong>(")

yields

<select><option>ABC <strong>(123)</option><option>XYZ <strong>(789)</option></select>

And gets correctly displayed (aside that <strong> has no effect). Also works fine when using <span> instead of <strong>

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜