2017-09-13 108 views
-1

我想添加一些内部每个th。表头是动态的生成依赖于数据库列使用JQuery追加一些文本到每个表头(th)

这是我有:

<table id="dynamic_id" class="table table-striped table-bordered"> 
    <thead> 
     <tr> 
      <th>Company Name</th> 
      <th>Email</th> 
      <th>Mobile</th> 
      <th>Address</th> 
     </tr> 

    </thead> 
    <tbody> 
     //body goes here 
    </tbody> 

    </tbody> 
</table> 

什么是ready事件使用jQuery期待

<th>Company Name 
      <span class="js-sorter-desc fa fa-chevron-down pull-right"></span> 
      <span class="js-sorter-asc fa fa-chevron-up pull-right"></span> 
</th> 

这应该是适用于每一个钍..

<span class="js-sorter-desc fa fa-chevron-down pull-right"></span> 
<span class="js-sorter-asc fa fa-chevron-up pull-right"> 
+0

http://api.jquery.com/append –

+0

欢迎堆栈溢出!请[参观],环顾四周,并通读[帮助],尤其是[*我如何提出一个好问题?](/帮助/如何问)做你的研究,包括看通过[jQuery API](http://api.jquery.com),并尝试完成这项工作。 **如果**在现场进行了更彻底的研究和[搜索](/帮助/搜索)后遇到*特定*问题,如果无法解决问题,请将您的尝试与您遇到的麻烦一起发布用它。人们会很乐意提供帮助。 –

+0

如果表格是动态的,那么计算列的数量,然后在每个内部使用 –

回答

1

你必须使用appendjQuery的方法。

此外,使用find方法,以获得全部thDOM元素。

$('.table.table-striped').find('thead tr th').append('<span class="js-sorter-desc fa fa-chevron-down pull-right"></span><span class="js-sorter-asc fa fa-chevron-up pull-right"></span>'); 
 
console.log($('.table.table-striped').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="dynamic_id" class="table table-striped table-bordered"> 
 
    <thead> 
 
     <tr> 
 
      <th>Company Name</th> 
 
      <th>Email</th> 
 
      <th>Mobile</th> 
 
      <th>Address</th> 
 
     </tr> 
 

 
    </thead> 
 
    <tbody> 
 
     //body goes here 
 
    </tbody> 
 
</table>

+0

你不需要'each()'在这里 –

+0

@RoryMcCrossan,谢谢你的观点!更新。 –

0

试试这个:

$(document).ready(function(){ 
    $('table').find('th')append('<span class="js-sorter-desc fa fa-chevron-down pull-right"></span><span class="js-sorter-asc fa fa-chevron-up pull-right">'); 
}); 
+0

这里你不需要'each()'。还有一点就是'id'是在运行时动态生成的,所以选择它可能不起作用。 –

+0

谢谢@RoryMcCrossan,我已经更新了我的答案。我已经使用'each'来获得动态代码。我知道,因为他想增加所有'',所以我们可以简单地把它当作选择器。 –

+0

我不知道这是什么意思,但你仍然不需要'each()''dynamic'或不是 –