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在键入时为所有元素设置一次,并在整个过程中保持唯一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 回答
0

用以下代码替换您的代码:

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

        if(!$(this).hasClass("idgenerated")){
            console.log( $(this).attr('id') );

            var t = GenerateID();

            $(this).attr('id','id-' + t);
            $(this).addClass("idgenerated");
            console.log($(this).prop("tagName") + ' = ' + t);
        }
});

工作小提琴

于 2015-08-08T17:21:28.160 回答