开发者

Variable affectation or IF statement IE issues

I have this (very) simple code:

var myvar = $('.selected').text();
if (myvar == "foo") { //do some stuff...}

It works i开发者_开发技巧n Firefox, not in IE_6. What's the problem?

Of course I alert($('.selected').text()) which gives me the right value.

And I change the code to:

var myvar = "foo";
if (myvar == "foo") { //do some stuff...}

Then it works in IE.

any explanation?


you are selecting a set of elements which have class="selected" -- if there is more than one element in the list you might end up with a few spaces before/after the actual "foo" text. Have you verified that is not the case? Try changing to using id=selected if possible -- i.e. $("#selected") which should give you one element only.


Is the code being called on page load? If so, have you wrapped it in a $(document).ready() function?

If not, it might be getting run while the DOM is still being constructed, and since IE is slower at building the DOM than Firefox, IE might not have built the .selected element by the time it runs this code, whereas Firefox could have.

I've seen a number of issues with JQuery that looked like cross-browser issues at first glance, but turned out to be just because of not using $(document).ready().

The white-space suggestions in the other answers also sound plausible, though.


It's possible that IE is giving you some whitespace that Firefox isn't (or vice-versa). Try this:

var myvar = $('.selected').text().replace(/^\s*(.*\S)\s*$/, '$1');

and see if that helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜