Javascript 删除使用 append 方法附加的 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11901174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
removing the div appended using append method
提问by user1531746
this is my code...append is working but removing is not working. how to remove the appended div?
这是我的代码...附加正在工作,但删除不起作用。如何删除附加的div?
<html>
<head>
<script type="text/javascript">
function view(){
$('body').append('<div class="added"><p>something</p></div>');
};
function close(){
$('.added').remove();
} ;
</script>
</head>
<body>
<a onclick="view();">something</a>
<a onclick="close();">close</a>
</body>
</html>
采纳答案by Esailija
Specify window.close
in your html handler:
window.close
在您的 html 处理程序中指定:
<a onclick="window.close();">close<a>
Otherwise close()
refers to the native close
method, which doesn't do anything.
否则close()
是指本地close
方法,它不做任何事情。
Here's how you would emulate it with a "javascript" (as opposed to inline html attribute) handler:
以下是使用“javascript”(而不是内联 html 属性)处理程序模拟它的方法:
elem.onclick = function(event) {
with(Window.prototype) {
with(document) {
with(this) {
close();
}
}
}
};
This is not exact reproduction (nor does it work in IE etc, that's not the point) but it would put the .close
in Window.prototype
in front of the global window.close
in the scope, so it shadows it. You can still refer to it explicitly with window.close()
.
这是不准确再现(也没有在IE等工作,这不是问题的关键),但它会把.close
在Window.prototype
全球面前window.close
的范围,所以它阴影。您仍然可以使用 明确引用它window.close()
。
You should also totally drop the above and use jQuery instead:
您还应该完全放弃上述内容并使用 jQuery 代替:
<a id="view">something<a>
<a id="close">close<a>
JS:
JS:
$(function() {
$("#view").click(function() {
$('body').append('<div class="added"><p>something</p></div>');
});
$("#close").click(function() {
$('.added').remove();
});
});?
Making an ajax request that fetches a html file to be appended:
发出一个获取要附加的 html 文件的 ajax 请求:
$.get("myhtml.html", function(html) {
$("body").append(html);
}, "html");
回答by Rnk Jangir
Don't know why but by putting another name to close function instead of close() it works
不知道为什么,但是通过将另一个名称用于 close 函数而不是 close() 它可以工作
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function view(){
$('body').append('<div class="added"><p>something</p></div>');
};
function close_it(){
$('.added').remove();
} ;
</script>
</head>
<body>
<a onclick="view();">something<a>
<a onclick="close_it();">close<a>
</body></html>