gpt4 book ai didi

javascript - 如何使用 jQuery 动态创建 HTML 表格?

转载 作者:行者123 更新时间:2023-12-03 21:34:58 24 4
gpt4 key购买 nike

我正在尝试使用 jQuery 动态创建如下所示的 HTML 表:

<table id='providersFormElementsTable'>
<tr>
<td>Nickname</td>
<td><input type="text" id="nickname" name="nickname"></td>
</tr>
<tr>
<td>CA Number</td>
<td><input type="text" id="account" name="account"></td>
</tr>
</table>

这是我的实际表格:

<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>

此方法将使用 idlabelText 创建 trtd 元素:

function createFormElement(id, labelText) {
// create a new textInputBox button using supplied parameters
var textInputBox = $('<input />').attr({
type: "text", id: id, name: id
});
// create a new textInputBox using supplied parameters
var inputTypeLable = $('<label />').append(textInputBox).append(labelText);

// append the new radio button and label
$('#providersFormElementsTable').append(inputTypeLable).append('<br />');
}

我还有一个值将显示为工具提示。

请帮我使用工具提示和tr td动态创建一个表格。

编辑:

我几乎已经完成了以下代码:

function createProviderFormFields(id, labelText,tooltip,regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = $('<input />').attr({
type: "text",
id: id, name: id,
title: tooltip
});

// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}

这里标签正常出现,但输入框没有出现,它显示文本框必须出现的[object Object]...

当我使用 console.log 打印 textInputBox 时,我得到以下内容:

[input#nickname,构造函数:函数,init:函数,选择器:“”,jquery:“1.7.2”,大小:函数…]

可能是什么问题?

感谢 @theghostofc 为我指明了道路...:)

最佳答案

您可以使用两个选项:

  1. 创建元素
  2. 内部HTML

创建元素是最快的方法(检查 here 。):

$(document.createElement('table'));

InnerHTML 是另一种流行的方法:

$("#foo").append("<div>hello world</div>"); // Check similar for table too.

查看 How to create a new table with rows using jQuery and wrap it inside div 上的真实示例.

There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.

编辑:

检查Dynamic creation of table with DOM

编辑2:

恕我直言,您正在混合对象和内部 HTML。让我们尝试使用纯内部 html 方法:

function createProviderFormFields(id, labelText, tooltip, regex) {
var tr = '<tr>' ;
// create a new textInputBox
var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';
// create a new Label Text
tr += '<td>' + labelText + '</td>';
tr += '<td>' + textInputBox + '</td>';
tr +='</tr>';
return tr;
}

关于javascript - 如何使用 jQuery 动态创建 HTML 表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18846253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com