【问题标题】:JQuery to dynamically assigning id to dynamically generated div, inside contenteditable divJQuery 将 id 动态分配给动态生成的 div,在 contenteditable div 内
【发布时间】:2013-02-28 02:11:28
【问题描述】:
<div class="pad" id="test" contenteditable="true" spellcheck="false">
    <div id="a0" class="lines" > text1</div>
</div>

我有一个内容可编辑的 div,其中有许多子 div,当用户按下 ENTER 键(使用 jQuery)转到下一行时,这些子 div 会动态生成。子 div 的一个示例是上面的 id= 'a0'

目标:动态生成唯一的id并分配给这些动态生成的子div。

下面是我用来完成这个任务的jQuery。

function getSelectedNode()

这是返回用户当前正在输入的行(即子 div)的 'id' 的函数。

var lineCount=0;

lineCount 变量的值等于生成的子 div 的总数。

 $(currentLine).next().attr('id','a'+(++lineCount));

这里currentLine包含用户当前正在输入的行的 id。按ENTER键时,新div在当前div之后自动生成,我尝试使用.next()访问并尝试使用.attr('id','a'+(++lineCount))为其分配一个新的ID。

如果我在 jQuery 的选择器子句中传递绝对值,则分配新 id 的过程效果很好,即:

$('#a0').next().attr('id','a'+(++lineCount));

而不是

$(currentLine).next().attr('id','a'+(++lineCount));

var lineCount = 0;
var currentLine = "#a0";

function getSelectedNode() {
    if (document.selection) 
        return document.selection.createRange().parentElement();
    else {
        var selection = window.getSelection();

        if (selection.rangeCount > 0) 
          return selection.getRangeAt(0).startContainer.parentNode;
    }
}


$('.pad').keypress(function (event) {

    var keycode = (event.keyCode ? event.keyCode : event.which);

    if (keycode == '13') {
        var sn = getSelectedNode();
        currentLine = "#" + sn.getAttribute('id');

        $(currentLine).next().attr('id', 'a' + (++lineCount));
    }
});

【问题讨论】:

  • 你赋值后currentLine的值是多少?
  • 根据这一行 'currentLine = "#" + sn.getAttribute('id');' ,currentLine 的值将始终等于用户当前正在输入的行的 'id'。

标签: javascript jquery html contenteditable attr


【解决方案1】:

Javascript 是单线程的,因此您可以为此使用 int...

var indexer = 0;
function getUniqueId(){
   indexer++;
   return indexer.toString();
}

警告:我不建议在大多数 Web 应用程序中在文档级别声明函数和属性。一旦你有了这个方法,它就很容易实现......

$("<div id='myDiv" + getUniqueId() + "' />");

【讨论】:

  • 感谢您的回答,但这不是我想要的。我需要为 已经存在的 div (我在上面描述的那个' $(currentLine).next() ' )分配唯一的 id 并且 不要创建一个新的 div新身份证。这是因为我正在尝试制作一个文本编辑器,其中每一行都有一个唯一的 id(并且行数 = 用户在 contenteditable div 中键入的行数)
  • 如果您可以创建一个代码示例的 jsbin,我可能会弄明白,但是查看代码,我能想到的可能是 currentLine 设置不正确?你在那里设置断点了吗?
  • [jsbin.com/osugos/7/edit](jsbin.com/osugos/7/edit) 在 Mozilla Firefox 和 Internet Explorer 中无法正常工作。 它仅适用于谷歌浏览器,但我在 jsbin 链接中描述了一些小错误。.
猜你喜欢
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多