在DIV中使用.data附加到DIV中

时间:2016-05-24 18:02:10

标签: javascript jquery html append draggable

我正在尝试将 div with div inside 应用到我页面上的特定元素,并使用 appendTo ,然后将其设置为可拖动。使用 appendTo 进行单独潜水并使其可拖动工作正常。我无法弄清楚的是如何将div放在我使用 appendTo 的div中。

我将发布首先运行的脚本,然后发布不具有额外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);

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

1 个答案:

答案 0 :(得分:1)

您要做的是将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);
相关问题