我试图在html表中追加表头。
它附加,但它插入一个休息并附加在下一行。如何克服这个?
Plz帮助。提前致谢。检查下面的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<table id="test">
<thead>
<th> Column 1</th>
<th> Column 2</th>
<th> Column 3</th>
</thead>
</table>
<button> Click Me</button>
<script>
$('#test >thead').append('<th> Column 4</th>');
</script>
</body>
</html>
答案 0 :(得分:4)
代码无效的原因: -
如果您在浏览器控制台上查看呈现的HTML 您的给定代码 ,那么您将<tr></tr>
自动介绍< / em> arround <th></th>
这就是为什么jQuery在换行符中附加<th> Column 4</th>
。 (一些足够聪明的浏览器会自动将它们设为HTML结构) 强>
您需要执行以下操作(自己在HTML中添加tr
并更改jQuery): -
$('#test >thead tr').append('<th> Column 4</th>');
工作示例: -
$('#test >thead tr').append('<th> Column 4</th>');
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<table id="test">
<thead>
<tr><!-- add it yourself-->
<th> Column 1</th>
<th> Column 2</th>
<th> Column 3</th>
</tr><!-- tr ended -->
</thead>
</table>
<button> Click Me</button>
</body>
</html>
答案 1 :(得分:4)
1)在thead内部遗漏tr
。
2)你试图将$('#test >thead')
附加到thead中。但是在浏览器中你可以看到有一个tr括在你的列名中。所以它会附加在tr
之外。所以你需要像$('#test >thead tr').append('<th> Column 4</th>');
$('#test >thead tr').append('<th> Column 4</th>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<table id="test">
<thead>
<tr>
<th> Column 1</th>
<th> Column 2</th>
<th> Column 3</th>
</tr>
</thead>
</table>
<button> Click Me</button>
</body>
</html>
答案 2 :(得分:4)
$('#test > thead tr').append('<th> Column 4</th>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="test">
<thead>
<tr>
<th> Column 1</th>
<th> Column 2</th>
<th> Column 3</th>
</tr>
</thead>
</table>
<button> Click Me</button>
tr
答案 3 :(得分:1)
此代码也很有帮助
<table id="test">
<thead>
//<tr> tag added which is missing in your code
<tr>
<th> Column 1</th>
<th> Column 2</th>
<th> Column 3</th>
</tr>
</thead>
</table>
<button> Click Me</button>
//below is the code inside <script></script>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
$('#test').find('thead tr').append('<th> Column 4</th>');
</script>