简体   繁体   English

如何在带有自定义html的jquery数据表中为每一列添加一行,从而将html代码保留在模板中并将javascript代码保留在单独的文件中?

[英]How to add a row in a jquery datatable with custom html for each column keeping html code in template and javascript code in separate files?

I have a datatable. 我有一个数据表。 I want to simply add a row or delete dynamically. 我只想添加一行或动态删除。 For deleting the row we simply use fnRowDelete() function which makes all task easy. 要删除该行,我们只需使用fnRowDelete()函数即可轻松完成所有任务。

<table>
  <tr>
    <td><p>sr no</p></td>
    <td><div>First name</div></td>
    <td><div>Last name</div></td>
  </tr>
</table>

However adding a new row using fnAddData(1,"john","doe") does the job but it will add a row by adding this data directly inside the tag with no custom html. 但是,使用fnAddData(1,“ john”,“ doe”)添加新行可以完成此工作,但是它将通过在标签内直接添加此数据而没有自定义html来添加一行。

<table>
  <tr>
    <td>1</td>
    <td>john</td>
    <td>doe</td>
  </tr>
</table>

Here i want to add this row with its html tags as well. 在这里,我也想添加此行及其html标签。 if we pass html as string in the function fnAddData() to get required output, we will not be able to make both javascript and html code separate (use of template). 如果我们在函数fnAddData()中将html作为字符串传递以获取所需的输出,则将无法使javascript和html代码分开(使用模板)。

Is there any way how i can keep both javascript and html code in different file and still be able to add a row in required format. 有什么办法可以将javascript和html代码保留在不同的文件中,并且仍然能够以所需格式添加一行。

Required sample output:- 所需样本输出:-

<table>
  <tr>
    <td><p>1</p></td>
    <td><div>john</div></td>
    <td><div>doe</div></td>
  </tr>
</table>

The better way to do is add custom template to your data-table rows. 更好的方法是将自定义模板添加到数据表行中。

 "columnDefs": [ {
        "targets": -1,
        "data": null,
        "defaultContent": "<button>Click!</button>"
    } ]

When Data is null, it will take from default template. 如果Data为空,它将取自默认模板。 If you want, you can format the data with the template according to your requirement. 如果需要,可以根据需要使用模板格式化数据。

use .html() to append. 使用.html()附加。 like this 像这样

$( "td" ).html( "<p>+'jsonData.Number'+</p>" );

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

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