1

私のコードを見てください:

// is_array function
function is_array(input){ return typeof(input)=='object'&&(input instanceof Array); }

// Check if cos_in is an array. If is not, create him
if(!is_array(cos_in))
{
    var cos_in = new Array();
}

// Onclick function
function cos(pret,box,configuratie)
{
    // Create a value (is different on every click; using different box)
    cos_in[box] = box + '|||' + pret + '|||' + configuratie + '||||';

    // Insert values from array in some div with #cos id
    $("#cos").html(cos_in.join('||||'));
}

私の問題は、id #cos を持つ div の開始値が「test-empty」であり、onclick 関数が実行されるたびに、div に関数からの値が必要であることです。しかし、空のdivを返します。

助けてください。

4

2 に答える 2

0

これは、使用できる単純なラッパーです。

function join(input, str) {
    if(typeof(input) === 'object') {
        if(input instanceof Array) {
            return input.join(str);
        } else {
            var tmp = [];
            for(var x in input) {
                if(input.hasOwnProperty(x)) {
                    tmp.push(input[x]);
                }
            }
            return tmp.join(str);
        }
    }
    return input;
}

/* ... */

$("#cos").html( join(cos_in, '||||') );

ただし、実際には言語間で異なる必要があります。少なくとも PHP と比較すると、JavaScript は期待どおりに機能しない可能性があります。

于 2013-01-28T22:25:36.557 に答える
0

このコードは大幅に改善できますが、ここで最初の問題を解決しようとしました。

クリックするたびに結果を追加しますか? 結合はどこにありますか? キーまたは値を結合しようとしていますか? 今のところ、キーではなく値が必要だと思います。

window.cos_in = window.cos_in && window.cos_in instanceof Array ? window.cos_in : []

// Onclick function
function cos(pret,box,configuratie)
{
    // Create a value (is different on every click; using different box)
    cos_in.push(box + '|||' + pret + '|||' + configuratie + '||||');

    // Insert values from array in some div with #cos id
    $("#cos").html(cos_in.join('||||'));
}

少し繰り返して、読みやすい/理解しやすいものにします。


これは、あなたがしていることのよりクリーンな例です。さらに改善するには、リンクとパラメーターを使用してどこに行くのかを知る必要があります。

var cos = (function (cos_in) {

    return function cos(pret, box, configuratie) {
        // Create a value (is different on every click; using different box)
        cos_in.push(box + '|||' + pret + '|||' + configuratie + '||||');

        // Insert values from array in some div with #cos id
        $("#cos").text(cos_in.join('||||'));
    };

}([]));

配列の代わりにオブジェクトバージョンの例を次に示します...

var cos = (function (cos_in) {

    return function cos(pret, box, configuratie) {
        // Create a value (is different on every click; using different box)
        cos_in[box] = (box + '|||' + pret + '|||' + configuratie + '||||');

        // Insert values from array in some div with #cos id
        $("#cos").text(Object.keys(cos_in).join('||||'));
    };

}({}));
于 2013-01-28T22:20:56.500 に答える