我有一张价值表。
<table id="myTable">
<tr>
<th title="Text to copy to list">header 1</th>
<th title="Text to copy to list">header 2</th>
<th title="Text to copy to list">header 3</th>
</tr>
<tr>
<td>Value 1</td>
<td>Value 2</td>
<td>Value 3</td>
</tr>
</table>
<div id="selectedVlues"></div>
我需要能够点击带有值并将该值添加到#selectedVlues div,同时向该列添加class =“added”。
我需要能够选择任意数量的th并将它们列在另一个之下。
<div id="selectedVlues">
header 2<br>
header 3<br>
</div>
如果我点击表格标题或列表中的所选项目,则需要从列表中删除该项目并从列中删除class =“added”。
到目前为止,我只有这个:
$(".myTable th").click(function() {
var headerVal = $(this).text();
$("#selectedVlues").text(catVal+"<br>");
});
不确定如何添加剩下的......
答案 0 :(得分:1)
$("#myTable th").click(function() {
var column_header = $(this);
var column_rows = $('#myTable tr td:nth-child(' + (column_header.index() + 1) + ')');
if (column_header.hasClass('added')) {
$('#selectedValues #' + column_header.index()).remove();
column_header.removeClass('added');
}
else {
$('#selectedValues').append('<span id="' + column_header.index() + '">' + column_header.text() + '</span>');
column_header.addClass('added');
}
column_rows.each(function(i, row) {
if ($(row).hasClass('added')) {
$(row).removeClass('added');
}
else {
$(row).addClass('added');
}
});
});
编辑:抱歉,更新了回复。
编辑2:根据评论更新并修复了语法错误。
答案 1 :(得分:1)
像这样的东西
var $myTable = $('#myTable'),
$headers = $('#myTable th'),
$cells = $('#myTable td'),
$selectedValues = $('#selectedValues');
$headers.click(function() {
// clicked header
var $this = $(this);
if ($this.hasClass('added')) {
// remove added class from column
$this.removeClass('added');
$cells.each(function() {
var $cell = $(this);
if ($cell.index() === $this.index()) {
$cell.removeClass('added')
}
});
// remove from selected values
$selectedValues.find(':contains("' + $this.text() + '")').remove();
} else {
// add class
$this.addClass('added');
$cells.each(function() {
var $cell = $(this);
if ($cell.index() === $this.index()) {
$cell.addClass('added')
}
});
$selectedValues.append('<li title="remove">' + $this.text() + '</li>');
}
});
$selectedValues.delegate('li', 'click', function() {
// clicked list item
var $this = $(this);
$header = $headers.filter(':contains("' + $this.text() + '")');
// remove 'added' class
$header.removeClass('added');
$cells.each(function() {
var $cell = $(this);
if ($cell.index() === $header.index()) {
$cell.removeClass('added')
}
});
$this.remove();
});
答案 2 :(得分:0)
尝试使用此Jquery
$("#myTable th").click(function() {
var table_value = $(this).text();
$("#selectedVlues").append(table_value+'<br />').addClass('added');
});
答案 3 :(得分:0)
$(function(){
$("#myTable th").click(function() {
debugger;
var headerVal = $(this).text();
$("#selectedVlues").html(headerVal+"<br>");
indexVal = $(this).index();
$("#myTable").find("td").eq(indexVal).addClass("added");
});
});
检查出来