質問

I'm having a problem and i don't know what i'm doing wrong.Well,
I'm parsing an xml file with php.The if conditiondoesn't work for some reason. Talking about this line: if (( '<?php echo $item['temp'] ?>' >= "37.0 °C") ) {
I have no idea why this line is not working.

    <?php foreach ( $item_array as $item ) : ?> 

                            var latlng = new google.maps.LatLng(parseFloat(<?php echo $item['glat']; ?>),
                                                                parseFloat(<?php echo $item['glon']; ?>));

                            if (( '<?php echo $item['temp'] ?>' >= "37.0 °C") ) {
                                alert('<?php echo $item['temp']; ?>');
                                var contentString = '<?php echo $item['title']; ?>' + ' , ' + '<?php echo $item['temp']; ?>' ;
                                var marker1 = createMarker1( contentString,latlng,hot );
                            }
        var hot   = 'weather_icons/hot.png';
        function createMarker1( contentString,latlng,hot ) {
                            var marker1 = new google.maps.Marker({
                            position: latlng,
                            map: map,
                            icon: hot
                            });
                        google.maps.event.addListener( marker1, "click", function() {
                        if (infowindow) infowindow.close();
                            infowindow = new google.maps.InfoWindow({
                            content: contentString
                            });
                            infowindow.open(map, marker1);
                        });
                        return marker1;
        }
    <?php endforeach; ?>

A sample of the xml file:

<rss version="2.0">
<channel>    
<item>
    <title>Salonika</title>
    <temp>6.7 °C</temp>
    <glat>40.422726139672626</glat>
    <glon>22.93392777442932</glon>
</item>
</channel>
</rss>
役に立ちましたか?

解決

You're comparing strings, not numbers. The string "6.7 °C" is greater than the string "37.0 °C". When comparing strings, JavaScript compares them "character" by "character" (technically, they're not characters but code units in UTF-16, but that's a technical detail). The character "6" is greater than the character "3", so the comparison doesn't have to look any further; it knows that the string starting with "6" is "greater than" the string starting with "3".

I would recommend modifying the PHP to output a number rather than a string. But if you want to leave the PHP as it, you can deal with this in the JavaScript:

if ( parseFloat('<?php echo $item['temp'] ?>') >= 37 ) {

parseFloat will parse the beginning of the string into a number (it assumes base 10), stopping at the first non-number character (in this case, the space). Note that I've changed what it's comparing to, as well, and gotten rid of the extra () (they were harmless, but pointless).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top