DIV 在 DIV appendTo 内与 .data

DIV inside of DIV appendTo with .data

我正在尝试将 div 与 div inside 应用于我页面上的特定元素,并使用 appendTo 然后让它可以拖动。应用带有 appendTo 的唯一 dive 并使其可拖动效果很好。我想不通的是如何将 div 放在我使用 appendTo 的 div 中。

我将 post 最先起作用的脚本,然后是不起作用的脚本,其中包含额外的 div。

有效的脚本:

$('<div>' + rText[i] + '</div>').data('number', next[i]).attr('id', +next[i]).attr('class', 'rtitle').appendTo($("#" + id).parent()).draggable({
  containment: '.site-wrapper',
  stack: '#testpile div',
  cursor: 'move',
  revert: true
}).hide().fadeIn(2000);

脚本不起作用:

$('<div>' + ('<div>' + rText[i] + '</div>').data('number', next[i]).attr('id', +next[i]).attr('class', 'rtext text-justify') + '</div>').data('number', next[i]).attr('id', +next[i]).attr('class', 'rtitle').appendTo($("#" + id).parent()).draggable({
  containment: '.site-wrapper',
  stack: '#testpile div',
  cursor: 'move',
  revert: true
}).hide().fadeIn(2000);

我很确定我的语法不正确,或者我只是使用了错误的机制来做我想做的事情。

你想做的是将 jQuery 对象和 HTML 字符串和函数结合起来,这就是问题所在。

第一条规则是尝试以对您有意义的方式格式化代码。这样就很容易找出到底哪里出了问题。

让我们尝试分解您的代码。

这部分

$('<div>' + ('<div>' + rText[i] + '</div>').data('number', next[i]).attr('id', +next[i]).attr('class', 'rtext text-justify') + '</div>')

应该是这样的

$('<div>')
  .append(
    $('<div>' + rText[i] + '</div>')
      .data('number', next[i])
      .attr('id', +next[i])
      .attr('class', 'rtext text-justify')
  )

完整代码

$('<div>')
  .append(
    $('<div>' + rText[i] + '</div>')
      .data('number', next[i])
      .attr('id', +next[i])
      .attr('class', 'rtext text-justify')
  )
  .data('number', next[i]).attr('id', +next[i]).attr('class', 'rtitle')
  .appendTo($("#" + id).parent())
  .draggable({
    containment: '.site-wrapper',
    stack: '#testpile div',
    cursor: 'move',
    revert: true
  }).hide().fadeIn(2000);