1

特定のデータ属性を持つページのすべての要素をドロップダウンに置き換えるために、このコードを作成しました。私が持っていたとしましょう:

<span data-what="partyBox"></span>

ドロップダウンに置き換えられます。コードはうまく機能しますが、例外があります。後で、現在のタグのすべての属性 (たとえば、すべてのデータ属性またはその他の割り当てられた属性) を割り当てたいと思いました。つまり、spanこの場合は、作成したドロップダウンに割り当てられるタグです。しかし、これを達成するのに問題があります。つまり、これらすべての属性がドロップダウンに適用されません。これが私のコードです:

var mould = {

    partyBox        :   $.parseHTML('<select name="mouldedParty"><option value="-1" selected disabled>Select Party</option></select>'),

    init            :   function (){ },

    process         :   function (container) {
                            var pBox     = $(mould.partyBox);
                            var pBoxes   = $(container).find('[data-what=partyBox]');

                            pBox.css({
                                'padding'    : '10px',
                                'border'     : '1px solid #ccc',
                                'background' : '#368EE0',
                                'color'      : 'white',
                                'cursor'     : 'pointer'
                            });

                            $(pBoxes).each(function(index, elem){
                                var attributes = elem.attributes;
                                var test = $(elem).replaceWith(pBox);
                                test.attributes = attributes;

                            });

                            // pBoxes.replaceWith(pBox);

                        }
};

mould.process('body');

このコードの何が問題なのか誰か教えてください。これらの行を置換に使用したにもかかわらず、span タグのすべての属性がドロップダウンに適用されないのはなぜですか

            var attributes = elem.attributes;
            var test = $(elem).replaceWith(pBox);
            test.attributes = attributes;
4

1 に答える 1

2

attributes要素のプロパティを設定することはできません。できることは、ある要素から別の要素に属性をコピーすることだけです。

次のようなコードが解決策になる可能性があります。

$(pBoxes).each(function (index, elem) {
    var newBox = pBox.clone(true, true)[0]; // get a simple DOM element

    // loop through the old element's attributes and give them to the new element
    for (var name in elem.attributes) {
        newBox.setAttribute(name, elem.attributes[name].value);
    }

    // replace the old element with the new one
    var test = $(elem).replaceWith(newBox);
});

私はあなたのコードが少し混乱していることを認めているので、私のコードがあなたの目的に合っていることを 100% 保証することはできません...

于 2013-11-07T13:29:35.073 に答える