Javascript terms

I have a strange problem: my conditions do not work in javascript: /

this is my code:

var myposition = $("#audioWelcome").data("myposition");

/* condition */
if (myposition == "true") {
....
}

This is not true? see my example: http://jsfiddle.net/qqK5J/2/ conditions do not work and html (); or data (); doesn't work either.

what is wrong?

+4
source share
4 answers

To answer your question:

if (myposition == "true") {

does not work as expected, because myposition- this is a boolean value truethat is not equal to the value of string "true" .

You may wonder why mypositionis a boolean. This is because jQuery converts it to a boolean :

JavaScript ( , , , ).

, , , , booleans :

if (myposition) {
    $(this).html("afficher le lecteur");
    $('#audioWelcome').data('myposition', false);
} else {
    $(this).html("cacher le lecteur");
    $('#audioWelcome').data('myposition', true);

}

:

$(this).html(myposition ? "afficher le lecteur" : "cacher le lecteur");
$('#audioWelcome').data('myposition', !myposition);

DEMO

+4

:

if (myposition == true) {

JSFilddle :

http://jsfiddle.net/qqK5J/5/

:

    if (myposition == true) {

        $(this).html("afficher le lecteur");
        $('#audioWelcome').data('myposition', false);


    } else {

        $(this).html("cacher le lecteur");
        $('#audioWelcome').data('myposition', true);

    };

​​ :

http://jsfiddle.net/qqK5J/10/

+1

!

, javascript "" "" ,

@Kyo , , - . 3 .

@user3391179 , , ...

Using the method toStringon $("#audioWelcome").data("myposition")will cause the value "true" / "false" (string) to work as you would expect from them.

The code:

    var myposition = $("#audioWelcome").data("myposition").toString();
    /* changements via onclick */
    if (myposition == "true") {
        $(this).html("afficher le lecteur");
        $('#audioWelcome').data('myposition', false);
    } else if (myposition == "false") {
        $(this).html("cacher le lecteur");
        $('#audioWelcome').data('myposition', true);
    };

Demo: http://jsfiddle.net/qqK5J/8/

+1
source

It’s better to distinguish == true. Then people will not think that you are a VB5 developer

if (myposition){}
0
source

Source: https://habr.com/ru/post/1530716/


All Articles