comparing strings in javascript
I am comparing two strings that supposed to be equal. From some reason it thinks they are not.
this is t开发者_开发百科he code:
function(){
prev = $('h').value;
now = $('content').innerHTML;
alert(prev);
alert(now);
if(prev == now)
{
$('content').fade({ duration: 3.0, from: 0, to: 1 });
}
else{alert('lol');}
}
I made added the alert functions to be sure they are equal.
Any idea why it gives me the "alert('lol)" ?
Your strings are probably different, but it's hard to see leading and trailing whitespace in alert()
boxes. You can try to trim() the strings:
if ($.trim(prev) == $.trim(now)) {
$('content').fade({ duration: 3.0, from: 0, to: 1 });
}
Your code is incorrect:
You need to use val()
instead of value
with jQuery selector or convert it to DOM element with get
or [0]
shorthand to use value
.
value
gives you what is inside value
attribute while innerHTML
gives you the inner html of an element. You should either use value
for both elements or innerHTML
depending on the type of elements :)
Example:
prev = $('h').val();
now = $('content').val();
if(prev == now)
Or:
prev = $('h')[0].innerHTML;
now = $('content')[0].innerHTML;
if(prev == now)
Two strings may look the same in an alert box but not be the same. For example, spaces at the beginning or end of one of the strings.
I find if I have this problem, I can spot it more easily by adding markers to the string when I alert it, like so:
alert('['+mystring+']');
Also, console.log()
is a more powerful way to debug this sort of thing than alert()
. console.log()
is available in most modern browsers when using their built-in developer tools (in Firefox, you need to install the Firebug plugin for this).
If you find you have leading/trailing spaces to get rid of, you can do so very easily with a quick regex:
mystring = mystring.replace(/((^\s)|(\s$))/,'');
This will remove all white-space from the beginning and end of the string.
Hope that helps.
精彩评论