首页 > 解决方案 > 使用 createElement() 创建的新元素不接受全局命令

问题描述

我有一个包含许多可排序项目的可排序元素(我们称之为可排序容器)。我正在尝试创建一个按钮,该按钮将创建更多可排序容器,可以将其他可排序容器中的项目拖放到其中(如看板表)。

为此,我使用.createElement()附加适当的标签(在本例中为:<div>、、<ul><h2>

行为符合预期的元素如下所示:

<!-- a test container that behaves as excpected
this is able to have elements dragged from the main sortable
container and dropped into this div -->

<div class="container" style="background-color:#fff;">
  <h2>new category</h2>
    <ul class="sortable connectedSortable"> //when inspected with dev tools, class="sortable connectedSortable ui-sortable"
    </ul>
</div>

这是我的函数创建的元素,其行为与预期不符:

<div class="container" style="background-color:#fff;">
  <h2>new category</h2>
    <ul class="sortable connectedSortable ui-sortable">
    </ul>
</div>

我的问题是它们看起来相同,但行为方式似乎不同!我的目标是让<div>我的函数创建的标签能够<li>从其他标签拖放到其中<div>

我的职能

<script>
// function from sortable
  $(function() {
    $( ".sortable" ).sortable({
      connectWith: ".connectedSortable",
      receive: function( event, ui ) {
        $(this).css({"background-color":'#fff'});
      }
    }).disableSelection();


//trying to add a new container with this function
document.getElementById("btnAdd").onclick = function () {
  var h2 = document.createElement('h2');    //create h2 tag
    h2.textContent="new category"           //text = "new category"
  var ul = document.createElement('ul');    //create ul tag
    ul.className = "sortable connectedSortable ui-sortable"  //specify class name
  var div = document.createElement('div');    //create new div
    div.className="container"                // specify div class
    div.style.backgroundColor="#fff";        //specify div color
    document.getElementById('mainDiv').appendChild(div);    //append newly created div to a main div section
    div.appendChild(h2)    //append newly created h2 to new div
    div.appendChild(ul)   //append newly created ul to new div
    };
});
</script>

我的按钮触发功能

<!-- this is the button that triggers function -->
<body>
    <input type="button" id="btnAdd" value="Add New Category">
</body>

我感兴趣的元素

<div id="mainDiv">

  <!-- my main sortable container -->
  <div class="container" style="background-color:#fff;">
    <h2>All colors:<br /></h2>
    <p>Add as many categories as you'd like and start sorting!</p>
    <ul class="sortable connectedSortable">
      <li class="card">testing</li>
      <li class="card">testing</li>
      <li class="card">testing</li>
      <li class="card">testing</li>
      <li class="card">testing</li>
    </ul>
  </div>

  <!-- a test container that behaves as excpected
  this is able to have elements dragged from the main sortable container and dropped into this div -->
  <div class="container" style="background-color:#fff;">
    <h2>new category</h2>
      <ul class="sortable connectedSortable">
        <li class="card">testing</li>
      </ul>
  </div>
</div>
</html>

我正在使用的样式

<style>
  body {font-family:Arial;}
  h2 {margin:5px;}
  p{margin:5px;}
  input[type=text] {margin:10px}
  input[type=button] {margin:10px}
  .container {width: 20%; border: 1px solid; float:left; clear:right;margin:10px; border-radius: 5px;}
  .sortable { list-style-type: none; margin:0; padding:2px; min-height:30px; border-radius: 5px;}
  .sortable li { margin: 3px 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px;}
  .sortable li span { position: absolute; margin-left: -1.3em; }

  .card{background-color:#f2e2e2; border-radius:3px;}
</style>

标签: javascriptjqueryclassjquery-ui-sortablecreateelement

解决方案


简而言之,问题在于您只是在页面加载.sortable时使元素可排序。您之后添加的任何 HTML 都将无法排序,因为您尚未重新应用该功能。.sortable()

这是一个带有注释代码的交互式示例,应该有助于理解正在发生的事情:

$(function() {
    // sortable elements to be made sortable on page load
    var sortableElements = $(".sortable");

    // a clone of the "new category" drop zone
    var containerTemplate = $(".category-container").clone();

    // the main container where clones will be appended
    var mainDiv = $("#mainDiv");

    // on page load, pass all ".sortable" elements to the makeSortable() function
    makeSortable(sortableElements);

    // "Add New Category" button
    $("#btnAdd").click(function() {
        // get a new template - on its own, this isn't sortable yet as .sortable() hasn't been called on it
        var newContainer = containerTemplate.clone();

        // append to #mainDiv
        mainDiv.append(newContainer);

        // find the <ul> and pass it to the makeSortable() function
        makeSortable(newContainer.find(".sortable"));
    })

    // generic function which takes an element and applies jQuery's "sortable" functionality
    function makeSortable(element) {
        element.sortable({
            connectWith: ".connectedSortable",
            receive: function(event, ui) {
                $(this).css("background-color", "#fff");
            }
        }).disableSelection();
    }
})
body {
	font-family: Arial;
}
h2 {
	margin: 5px;
}
p {
	margin: 5px;
}
input[type=text] {
	margin: 10px
}
input[type=button] {
	margin: 10px
}
.container {
	width: 20%;
	border: 1px solid;
	float: left;
	clear: right;
	margin: 10px;
	border-radius: 5px;
}
.sortable {
	list-style-type: none;
	margin: 0;
	padding: 2px;
	min-height: 30px;
	border-radius: 5px;
}
.sortable li {
	margin: 3px 3px 3px 3px;
	padding: 0.4em;
	padding-left: 1.5em;
	font-size: 1.4em;
	height: 18px;
}
.sortable li span {
	position: absolute;
	margin-left: -1.3em;
}
.card {
	background-color: #f2e2e2;
	border-radius: 3px;
}

/* CSS additions for example */
#btnAdd {
  display: block;
}
<input type="button" id="btnAdd" value="Add New Category" />

<div id="mainDiv">
  <div class="container" style="background-color:#fff;">
    <h2>All colors:</h2>
    <p>Add as many categories as you'd like and start sorting!</p>
    <ul class="sortable connectedSortable">
      <li class="card">testing</li>
      <li class="card">testing</li>
      <li class="card">testing</li>
      <li class="card">testing</li>
      <li class="card">testing</li>
    </ul>
  </div>

  <div class="container category-container" style="background-color:#fff;">
    <h2>new category</h2>
    <ul class="sortable connectedSortable"></ul>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>


推荐阅读