gpt4 book ai didi

javascript : creating elements on first click and deleting the created element on second click

转载 作者:行者123 更新时间:2023-11-30 15:09:55 26 4
gpt4 key购买 nike

我的页面中有一个 div,我将使用它在另一个添加了类的 div 中生成 p 标记。

function creatorfunction() {
var u94 = document.getElementById("box").getAttribute("custom-data");
parau94 = document.createElement("p");
parau94.innerHTML = u94;
parau94.className = "u94cl";
creation = document.getElementById("generator");
creation.appendChild(parau94);
}
#generator {
background-color: #29BF97;
width: 200px;
height: 200px;
float: right;
display: inline-block;
}

#box {
background-color: #29BF97;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box" onclick="creatorfunction()" custom-data="you just clicked me"> click me </div>
<div id="generator">
</div>

这是我下一步要实现的目标。当我点击“点击我”时,它创建了 p 标签,但现在我想删除相同的 p 标签如果我再次点击“点击我”。

最佳答案

首先,如果您不使用选择和点击事件,为什么要添加 jquery?

无论如何,您需要添加一个小插件来处理切换功能。

然后调用 clickToggle,它接受 2 个函数并在每次点击时在它们之间切换。

//clickToggle plugin
(function($) {
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
}(jQuery));
//end plugin


$('#box').clickToggle(function() {
creatorfunction();
}, function() {
$('#generator').children().first().remove(); //removes the first child from #generator
});


function creatorfunction() {
var u94 = document.getElementById("box").getAttribute("custom-data");
parau94 = document.createElement("p");
parau94.innerHTML = u94;
parau94.className = "u94cl";
creation = document.getElementById("generator");
creation.appendChild(parau94);
}
#generator {
background-color: #29BF97;
width: 200px;
height: 200px;
float: right;
display: inline-block;
}

#box {
background-color: #29BF97;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box" custom-data="you just clicked me"> click me </div>
<div id="generator">
</div>

关于javascript : creating elements on first click and deleting the created element on second click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45261161/

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