Javascript 删除插入的HTML代码
我想知道如何删除选择某个单选按钮后出现的代码。我已经得到了它的生成,但是当我移除它时,整个身体都消失了,所以我只需要移除碎片Javascript 删除插入的HTML代码,javascript,jquery,html,Javascript,Jquery,Html,我想知道如何删除选择某个单选按钮后出现的代码。我已经得到了它的生成,但是当我移除它时,整个身体都消失了,所以我只需要移除碎片 <head> <style> input, label { line-height: 1.5em; } </style> <script src="http://code.jquery.com/jquery-latest.js"></scr
<head>
<style>
input, label {
line-height: 1.5em;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form>
<div>
<input type="radio" name="modtype" value="My Mods" id="mymods">
<label for="orange">My Mods</label>
</div>
<div>
<input type="radio" name="modtype" value="Group Mods" id="groupmods">
<label for="apple">Group Mods</label>
</div>
<div>
<input type="radio" name="modtype" value="Individual Mods" id="individualmods">
<label for="banana">Individual Mods</label>
</div>
<div id="modtype"></div>
</form>
<script>
$("input").on("click", function() {
$("#modtype").html($("input:checked").val() + " is selected! - Now Choose Mod! :)");
});
</script>
<script>
var appended = $('<div />').text('YOYOY');
var fragment = create('<div>Hello!</div><p>...</p>');
appended.id = 'appended';
$('input:radio[name="modtype"]').change(
function() {
if ($(this).val() == 'My Mods') {
document.body.insertBefore(fragment, document.body.childNodes[0]);
} else {
document.body.remove(fragment);
}
});
function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
</script>
</body>
</html>
您没有使用。请正确删除。您需要找到您的片段,将其放入jQuery对象中,然后在该jQuery对象上调用.remove
假设只有一个片段具有您给定的id,它可以简单如下:
$("#appended").remove();
要删除添加id=的片段,请执行以下操作
或者,如果您仍然有要删除的根DOM元素,则可以执行以下操作:
$(fragment).remove();
如果这是您要问的,这就是我如何删除某些元素的方法-您需要知道要删除的div的名称。请参阅下面的代码,并更改为您的值
var removeDiv= document.getElementById("your-div-id");
if (typeof removeDiv !== "undefined"){
if (removeDiv !== null){
document.getElementById('your-root-div-id').removeChild(removeDiv);
}
这将修复您的代码,我已在此处进行了测试: 简单更改: document.body.removefragment; 致: iffragment.parentNodefragment.parentNode.removefragment 1 当你这么做的时候:
document.body.insertBefore(fragment, document.body.childNodes[0]);
片段的childnodes中的元素已成为document.body的childnodes。因此片段不再具有childnodes。您必须找到创建jQuery或getElementxxxxxs的元素并删除它们
二,
要从主体中删除元素的方式不正确
document.body.remove(fragment);
你可以这样做:
document.body.removeChild(someChildNode); // dom api
$([elem/selector]).remove(); // jQuery
通过innerHTML注入元素时要小心。这不仅会使新生成的内容更难从其放置的位置中取出,而且还会出现一系列其他问题,如事件侦听器中断、选择器由于错误标记而中断等。您几乎应该始终使用appendChild或insertBefore添加元素。我将把答案留给知道如何通过库实现这一点的jQuery专家。