我需要一些代码来使用删除和切换类通过tg标记每个人的idee?代码工作正常,但我没有一些想法使用它。非常有意义,这对我很好
代码链接: https://jsfiddle.net/iandslevi/oonmaLxy/#&togetherjs=3K3nFjRir5
<html>
<head>
<title>Page Title</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<style>
.with{
background-color:red;
}
</style>
</head>
<body>
<table>
<tr>
<th class="ohne" >1</th>
<th class="ohne" >X</th>
<th class="ohne" >2</th>
</tr>
<tr>
<td class="ohne" numid="1" >team 1</td>
<td class="ohne" numid="2" >draw 1</td>
<td class="ohne" numid="3" >team 2</td
</tr>
<tr>
<td class="ohne" numid="4" >team 3</td>
<td class="ohne" numid="5" >draw 2</td>
<td class="ohne" numid="6" >team 4</td
</tr>
</table>
<ol id="list">
</ol>
<div id="result">
</div>
<script>
var sum = [];
$("document").ready(function (){
$('td').click(function (){
var numid = $(this).attr("numid");
sum.push(numid);
var addli = '<li numid="'+numid+'">'+numid +'<button class="remove"id="'+numid +'">X</button></li>';
$("#list").append(addli);
console.log(sum) ;
})
$("td").click(function(){
$(this).toggleClass("with");
});
})
$(document).on('click', '.remove', function() { $(this).parent().remove();
});
</script>
</body>
</html>
答案 0 :(得分:0)
当您点击它时,您的代码会向with
元素添加td
类。它还添加了一个单击它后从DOM中删除的按钮。
您尝试执行的操作是单击该按钮时,它还会删除添加该按钮的原始td
元素中的'with'类。
这是一个很好的工作示例:https://jsfiddle.net/oonmaLxy/1/
这就是代码本身:
$("td").click(function(){
$(this).toggleClass("with");
var $button = $('<button>X</button>');
$('<li></li>').append(
$(this).data("numid"),
$button
).appendTo("#list");
$button.data('numid', $(this).attr("numid")).click(function() {
$('td[numid="' + $(this).data('numid') + '"]').removeClass('with');
$(this).parent().remove();
});
});
此代码的作用是将click
事件绑定到td
元素:
$("td").click(function(){ .... });
在点击事件中,我正在执行以下步骤:
with
类添加到点击的元素:$(this).toggleClass("with");
var $button = $('<button>X</button>');
(稍后我将需要它)li
元素中,然后将li
添加到ID为list的ul
这是将按钮添加到列表中的代码:
$('<li></li>').append(
$(this).data("numid"),
$button
).appendTo("#list");
接下来是最重要的部分 - 这是我确保当您点击按钮时,它将从原始with
元素中删除td
类:
我要做的第一件事就是在按钮的数据中保存numid
元素的原始td
属性(使用$(this).attr("numid")
),所以当你单击它,它将知道它应该删除td
类with
,注意我现在正在使用我在步骤#2中创建的$button
变量,以便做到这一点:
$button.data('numid', $(this).attr("numid"))
最后一件事是将click
事件绑定到将删除该类的按钮:
.click(function() {
// Select a 'td' element with "numid" attribute equal to the button's numid stored in its data, and remove the 'with' class from it
$('td[numid="' + $(this).data('numid') + '"]').removeClass('with');
// Remove the button's parent 'li' from the DOM
$(this).parent().remove();
});