简体   繁体   English

jQuery可在嵌套元素中排序

[英]jQuery sortable in nested element

I have a list with categories and questions (which can both be added dynamically), at the moment I am able to sort the categories using jQuery sortable, but not the questions underneath the categories. 我有一个包含类别和问题的列表(都可以动态添加),目前我可以使用jQuery sortable对类别进行排序,但不能对类别下面的问题进行排序。

I've tried just adding another .sortable function on the question wrap element but it is not responding at all. 我试过在问题自动换行元素上添加另一个.sortable函数,但它根本没有响应。

My code at the moment: 我目前的代码:

// HTML template for new fields
const template = `
<div class="row sortwrap">
  <div class="col-md-8">
    <input type="text" name="category[]" placeholder="" class="form-control name_list catinput" />
    <i class="mdi mdi-sort dragndrop"></i>
  <div class="questionlist questionwrap">
    <div class="row">
      <div class="col-md-8">
        <button class="btn btn-success questionbutton">Extra vraag</button>
        <input type="text" name="question[]" placeholder="1. Voeg een vraag toe" class="form-control name_list questioninput" />
      </div>
      <div class="col-md-4">

      </div>
    </div>
    </div>
  </div>
  <div class="col-md-4">
  <button id="addcategory" class="btn btn-danger btn_remove removebutton">X</button>
  </div>
</div>`;

const vraagTemplate = `
<div class="row" id="question">
  <div class="col-md-8">
    <input type="text" name="question[]" class="form-control name_list questioninput" />
  </div>
  <div class="col-md-4">
    <button class="btn btn-danger btn_remove">X</button>
  </div>
</div>`;
// Count numbers and change accordingly when field is deleted
function updatePlaceholders() {
  // Sortable code
// $('#dynamic_field').sortable( "refresh" );
  let df = $('#dynamic_field');
  df.find('input[name^=cat]').each(function(i) {
    $(this).attr("placeholder", i + 1 + ". Voeg een categorie toe");
  });
  df.find('.sortwrap').each(function(i) {
    $(this).attr("id", i + 1);
  });
  df.find('.questionlist').each(function() {
    $(this).find('input[name^=qu]').each(function(i) {
      $(this).attr("placeholder", i + 1 + ". Voeg een vraag toe");
    });
  });
}
// Append question template
$('#dynamic_field').on('click', '.questionbutton', function() {
  let $ql = $(this).closest('.questionlist');
  $ql.append($(vraagTemplate));
  updatePlaceholders();
});

// Delete
$('#dynamic_field').on('click', '.btn_remove', function() {
  $(this).closest('.row').remove();
  updatePlaceholders();
});
$('#addcategory').on('click', function() {
let t = $(template)
  $('#dynamic_field').append(t);
  updatePlaceholders();
});

$(function() {
  $('#addcategory').trigger('click');
  $('#question').sortable();
  $('#dynamic_field').sortable({
    cancel: '.questionwrap',
    placeholder: "ui-state-highlight"
  });

});

This is my sortable code: 这是我的可排序代码:

$(function() {
    $('#addcategory').trigger('click');
    $('#question').sortable();
    $('#dynamic_field').sortable({
    cancel: '.questionwrap',
    placeholder: "ui-state-highlight"
});

#question is the wrap of my question list and #dynamic_field is the wrap of my category element (the questions are also inside this element). #question是我的问题列表的包装,而#dynamic_field是我的category元素的包装(问题也位于此元素内)。

How can I make my questions also sortable? 如何使我的问题也可以分类? And also only make then sortable inside their parent div (so I can't drag a question from one category to the other but only within its own category). 而且也只能使它们在其父div内可排序(因此,我不能将问题从一个类别拖到另一个类别,而只能在其自己的类别内)。

One of the first thing I have noticed about your code is that the ID is repeated for each creation of a dynamic element. 关于您的代码,我注意到的第一件事是,每次创建动态元素时都会重复使用ID。 This will cause a lot of issues when you have 6 #question elements. 当您有6个#question元素时,这将导致很多问题。 This can be addressed by adding the ID to the element when it's created and creating a unique ID. 这可以通过在创建元素时将ID添加到元素并创建唯一ID来解决。 For example, if there are 0 #questions then you can count that and add 1. 例如,如果有0个#questions则可以将其计数并加1。

<div id="question-1"></div>
<script>
var id = $("[id|='question']").length + 1;
</script>

In this, id would be 2. there is one element that contains "question" and the |= selector will look for that before the - in a ID name. 在这种情况下, id为2。有一个元素包含“问题”,而ID的|=选择器将在-之前查找。 Can also use ^= selector. 也可以使用^=选择器。

Making use of handle will help a lot too. 利用handle也会有很大帮助。 This will help allow proper sorting of nested items versus their parents. 这将有助于对嵌套项与其父项进行正确排序。 Also containment is helpful here too unless you want to move them between lists. 除非您想在列表之间移动它们,否则containment在这里也很有帮助。

Consider the following code. 考虑以下代码。 It's a little clunky and I hope you can see what I am referring to. 这有点笨拙,希望您能明白我的意思。

 $(function() { function makeSortable(obj, options) { console.log("Make Sortable", obj); obj.sortable(options); obj.disableSelection(); } function updateSort(obj) { console.log("Update Sortable", obj); obj.sortable("refresh"); } function addQuestion(q, c) { console.log("Add Question", q, c); var makeSort = $("[id|='question']", c).length === 0; var question = $("<div>", { class: "question", id: "question-" + ($("div[id|='question']", c).length + 1) }); question.append($("<div>", { class: "col-md-8" }).html(q)); question.append($("<div>", { class: "col-md-4" }).html("<button class='btn btn-danger btn-remove'>X</button>")); question.appendTo($(".catcontent", c)); console.log(makeSort, question, c); if (makeSort) { makeSortable($(".catcontent", c), { containment: "parent", items: "> div.question" }); } else { updateSort($("[id|='question']", c).eq(0).parent()); } } function makeCategory(name) { console.log("Make Category", name); var makeSort = $("[id|='category']").length === 0; var cat = $("<div>", { class: "category ui-widget", id: "category-" + ($("[id|='category']").length + 1) }); cat.append($("<div>", { class: "cathead ui-widget-header" }).html(name + "<i class='btn btn-add-question'>+</i>")); cat.append($("<div>", { class: "catcontent ui-widget-content col-md-8" })); cat.appendTo($("#cat-wrapper")); if (makeSort) { makeSortable($("#cat-wrapper"), { handle: ".cathead", items: "> div.category" }); } else { updateSort($("#cat-wrapper")); } } $('#addcategory').on('click', function() { let t = $(template); $('#dynamic_field').append(t); updatePlaceholders(); }); $(".categorybutton").click(function(e) { e.preventDefault(); makeCategory($(".catinput").val()); $(".catinput").val(""); }); $(".catwrap").on("click", ".btn-add-question", function(e) { e.preventDefault(); var resp = prompt("Question to Add:"); addQuestion(resp, $(this).parent().parent()); }); }); 
 <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <script src="http://code.jquery.com/jquery-3.3.1.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div class="row sortwrap"> <div class="col-md-8"> New Category <input type="text" class="form-control catinput" placeholder="Category Name" /> </div> <div class="col-md-4"> <button class="btn btn-success categorybutton">Add</button> </div> </div> <div id="cat-wrapper" class="row catwrap"> </div> 

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM