1

私は次のことを試しました:

HTML:

<div contenteditable="true" id="editable"></div>

JS:

$('#editable').keyup(function() {
    addID();
});

function addID()
{
    $('#editable *').each(function() {

        var t = GenerateID();

        $(this).attr('id','id-' + t);

    });
}

function GenerateID() 
{
    var str = 'abcdefghijklmnopqrstuvwxyz0123456789';

    var alphabet = '', 
        genID = '';

    while(genID.length < 5)
    {
        alphabet = str.charAt(Math.floor(Math.random() * str.length)); 
        genID += alphabet;
    }

    return genID;
}

しかし、キーアップのたびに ID が変更され続けます。

id入力中にすべての要素に対して1回だけ設定し、全体で一意に保つにはどうすればよいdivですか?

JSFiddle

4

3 に答える 3

1

最終更新: 今、私はあなたのフィドルのコードをチェックしました。一意性のチェックはおそらく関数にすることができますが、それはあなたに任せます:

$('#editable').on( 'keyup', addID );


var count = 0;  // this will absolutely ensure that ID will be unique

function addID(){  

    var previousIDs = [];

    $('#editable *').each(function() {

        count++;
        var thisID = $(this).attr( 'id' );

        // let's check if we have duplicates:
        var index = 0, len = previousIDs.length, isDuplicate = false;

        for( index = 0; index < len; index++ ){
            if ( thisID === previousIDs[index] ) { 
                isDuplicate = true; 
                break;
            }
        }


        // now change the ID if needed:
        if (  isDuplicate    ||    ! thisID  ){

            var t = GenerateID();
            var newID = 'id-' + t + '-' + count;

            $(this).attr('id', newID);
            previousIDs.push( newID );

        }else{
            previousIDs.push( thisID );
        }

    });
}

働くフィドル

于 2015-08-08T17:15:37.960 に答える
0

これを試して:

$('#editable').keyup(addID);
function addID() {
    $('#editable *').each(function () {
        var t = GenerateID();
        var elem = $(this);
        var attr = elem.attr('id');
        if (!attr) {
            elem.attr('id', 'id-' + t);
        }
    });
}
/**
 * @return {string}
 */
function GenerateID() {
    var str = 'abcdefghijklmnopqrstuvwxyz0123456789';
    var alphabet = '',
            genID = '';
    while (genID.length < 5) {
        alphabet = str.charAt(Math.floor(Math.random() * str.length));
        genID += alphabet;
    }
    return genID;
}

また、ランダム文字列ジェネレーターが同じ文字列を再度生成する可能性があることも考慮してください。

于 2015-08-08T17:13:16.237 に答える