我正在尝试使用 jquery
创建一些 div,通过单击它们我可以将它们的文本添加到列表中,再次单击该 div 我可以从列表中删除该 div 的文本, 不是所有的人。
但是当我通过再次单击该 div 命令删除时,所有文本都从列表中删除
$(".first-div").on('click', function() {
$(this).toggleClass("div2 active");
let matn = $("<h3>" + $(this).html() + "</h3>");
if ($(this).hasClass("active")) {
$(".textbox").append(matn);
} else {
$(".textbox").children("h5").html($(this).html()).remove();
}
})
body {
padding: 3em;
}
.first-div {
padding: 0.5em 1.5em;
background-color: silver;
margin: 2em 0;
border: 2px solid silver;
}
.div2 {
border-color: red;
}
.text {
margin-top: 3em;
padding: 1em;
}
.textbox {
padding: 1.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<section>
<div class="first-div">
<h5>text1</h5>
</div>
<div class="first-div">
<h5>text2</h5>
</div>
<div class="first-div">
<h5>text3</h5>
</div>
</section>
<section class="text">
<div class="textbox"></div>
</section>
</body>
最佳答案
一个更简单的模式是在每次进行更改时构建整个列表,而不是在选择/取消选择元素时必须维护数组。
另请注意,您当前的示例是嵌套 <h5>
<h3>
中的元素, 这是无效的。
$(".first-div").on('click', function() {
$(this).toggleClass("div2 active");
let matn = $('.first-div.active').map(function() {
return $(this).html();
}).get();
$(".textbox").html(matn);
})
body {
padding: 3em;
}
.first-div {
padding: 0.5em 1.5em;
background-color: silver;
margin: 2em 0;
border: 2px solid silver;
}
.div2 {
border-color: red;
}
.text {
margin-top: 3em;
padding: 1em;
}
.textbox {
padding: 1.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<div class="first-div">
<h5>text1</h5>
</div>
<div class="first-div">
<h5>text2</h5>
</div>
<div class="first-div">
<h5>text3</h5>
</div>
</section>
<section class="text">
<div class="textbox"></div>
</section>
关于javascript - 通过单击将 div 的文本添加到列表中,并通过单击相同的 div 将其删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53295941/