简体   繁体   中英

How can I compare two hex values?

I need to compare two hex values that are coming from a xml tag attribute field, I'm trying this:

var fill = $(this).attr( "fill" );
// console.log( fill.toString(16) );
if ( fill === "#FF00FF" )

But is not working any ideas?

I think you have to use 2 equal signs there, try this...

var fill = $(this).attr( "fill" );
if ( fill == "#FF00FF" )

If that doesn't work, then you probably not identifying $(this)

attr returns a string, there's no need to call toString on it (and the argument will be ignored, because String 's toString doesn't take an argument).

Your code is assuming a couple of things:

  1. That the attribute comes back in #hex form (if it's a color value, this is not reliably true cross-browser).

  2. That it will be in all upper case.

Not knowing what you see when you log the value, I'll just address the second part:

var fill = $(this).attr( "fill" );
if ( fill.toUpperCase() === "#FF00FF" )

If fill is a color, then it might be returned in RGB-format. And when you log it you write toString() . Either compare it with a RGB-value or compare it with a string as fill.toString(16)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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