【问题标题】:How to position checkbox on top of DIV while creating checkbox inside of foreach如何在 foreach 内创建复选框时将复选框放置在 DIV 顶部
【发布时间】:2015-06-17 07:12:15
【问题描述】:

这是我的输出

这是我的 .html

    <td class="category" colspan ="2" id="tdcategory1">
         <div id="category1" style="border:none !important; overflow:hidden; width:auto; height:auto">
         </div>
    </td>

我的程序是我将在 id="tdcategory1" 内创建复选框 我将在 id="category1"

中创建许多复选框

这是我的 .js

     var div = $('#tdcategory1');
     var input = $('<input />', { type: 'checkbox', name: "chkallcategory1", id: "chkallcategory1", value: 1, style: "cursor:pointer" });
     input.appendTo(div);

     $.each(data.Records, function (e, key, value) {
      var div = $('#category1');
           var input = $('<input />', { type: 'checkbox', name: cate_name, id: cate_name + '_' + key.id, value: key.id, style: "cursor:pointer" });
         input.appendTo(div);
     });

问题是我创建的第一个复选框位于#category1 div 的底部

【问题讨论】:

  • 因为您将 'top' 复选框附加到 TD,但将任何以下复选框附加到此 TD 内的前 DIV
  • 试试这个$('#category1').before(input);

标签: jquery css arrays


【解决方案1】:

使用 prependto() 函数。

var div = $('#tdcategory1');
 var input = $('<input />', { type: 'checkbox', name: "chkallcategory1", id: "chkallcategory1", value: 1, style: "cursor:pointer" });
 input.prependTo(div);

查看this link了解更多信息。

【讨论】:

    【解决方案2】:

    当您为第一个复选框执行appendTo 时,它将在您的页面中创建以下标记:

    <td class="category" colspan ="2" id="tdcategory1">
             <div id="category1" style="border:none !important; overflow:hidden; width:auto; height:auto">
             </div>
             <!-- checkbox here -->
    </td>
    

    所以你应该在 id 为 category1 的 div 之前添加它

    方法#1

    您应该使用insertBefore 方法,如下所示:

    var div = $('#category1');
    var input = $('<input />', { type: 'checkbox', name: "chkallcategory1", id: "chkallcategory1", value: 1, style: "cursor:pointer" });
    input.insertBefore(div);
    
    $.each(data.Records, function (e, key, value) {
      var div = $('#category1');
      var input = $('<input />', { type: 'checkbox', name: cate_name, id: cate_name + '_' + key.id, value: key.id, style: "cursor:pointer" });
      input.appendTo(div);
    });
    

    方法#2

    如果您无权访问元素并想首先添加,您应该使用prependTo,如下所示

    var div = $('#tdcategory1');
    var input = $('<input />', { type: 'checkbox', name: "chkallcategory1", id: "chkallcategory1", value: 1, style: "cursor:pointer" });
    input.prependTo(div);
    
    $.each(data.Records, function (e, key, value) {
      var div = $('#category1');
      var input = $('<input />', { type: 'checkbox', name: cate_name, id: cate_name + '_' + key.id, value: key.id, style: "cursor:pointer" });
      input.appendTo(div);
    });
    

    【讨论】:

    • 这个很好 input.insertBefore(div);感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 2023-03-15
    • 2014-02-04
    • 1970-01-01
    相关资源
    最近更新 更多