JavaScript


Snippets
Ekkart Kleinod  • 

Was man so brauchen könnte...

Konsolenausgabe

console.log('Hallo Welt.');

Funktion definieren

function doSomething(param) {
    return true;
}

Arrays

[] statt new Array() nehmen

var arrNames = []; // var arrNames = ["a", "b"];

arrNames.push("abc");

console.log(arrNames);

Inhalt eines Verzeichnisses/einer Datei lesen

Auslesen und gelesene Information nutzen. fetch arbeitet asynchron, daher die Konstruktion mit then.

Mit fetch kann auch eine Datei gelesen werden.

function getDirectoryContent(dirname) {

    return fetch(dirname)
        .then(res => res.text())
        .then(text => {

            var arrNames = [];
            $('a', text).each(function() {

                var contentname = this.href.replace(window.location.href, '');

                if (contentname != "") {
                    arrNames.push(dirname + contentname);
                }
            });

            return arrNames;

        });

}

getDirectoryContent('/tracks/')
    .then(arrNames => $.each(arrNames, function() {
        console.log("- " + this);
    }));

for...each mit jQuery

Direkt nutzen

var arrNames = ["a", "b", "c"];
$.each(arrNames, function() {
    console.log(this);
});

Mit jQuery-Objekten nutzen

$('a', text).each(function() {
    console.log(this);
});

for...each mit jQuery

Direkt nutzen

var arrNames = ["a", "b", "c"];
$.each(arrNames, function() {
    console.log(this);
});

JSON mit jQuery

$.getJSON(`/filename.json`, function() {
    console.log("success");
})
    .done(function() {
        console.log("second success");
    })
    .fail(function(jqxhr, textStatus, error) {
        var errMsg = "error: " + textStatus + ", " + error;
        console.log(errMsg);
        alert(errMsg);
    })
    .always(function() {
        console.log("complete");
    });

oder entfernter

var jsonData = $.getJSON(`/filename.json`);

$.when(jsonData).done(
    function() {
        console.log("second success");
    }
);

$.when(jsonData).fail(
    function(jqxhr, textStatus, error) {
        var errMsg = "error: " + textStatus + ", " + error;
        console.log(errMsg);
        alert(errMsg);
    }
);