Javascript 为什么empty()方法在jQuery中不起作用?
我的代码非常简单。 这是我对jQuery的练习Javascript 为什么empty()方法在jQuery中不起作用?,javascript,jquery,Javascript,Jquery,我的代码非常简单。 这是我对jQuery的练习 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>node_jQueryAPI</title> <script src="jquery/jquery.js"></script> </head> <body> &
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>node_jQueryAPI</title>
<script src="jquery/jquery.js"></script>
</head>
<body>
<div class="target" id="target1">
content1
</div>
<div class="target" id="target2">
content2
</div>
</body>
</html>
这在Chrome控制台中运行良好
但是如果我使用JavaScript代码,比如
var targets = document.getElementsByClassName('target');
targets[0].remove(); // This is working well
targets[0].empty(); // This is never working!!!! This is my Question!, Why!?!!??
请帮帮我~!!谢谢在普通JavaScript中没有名为
empty()
的方法。如果要清空元素,有几种方法。最直接的方法之一是简单地将元素的内部HTML分配给空字符串,如下所示:
document.querySelector(“div”).innerHTML=“”代码>
以下div现在为空
ABC
如果您试图测试jQuery方法remove()
和empty()
,那么您需要包装在jQuery中检索的DOM元素,以便对其调用jQuery函数。像这样:
var targets = document.getElementsByClassName('target');
$(targets[0]).remove(); //will remove the first element with class `target` from the DOM
$(targets[1]).empty(); //will empty the contents of the second element with class `target` in the DOM (i.e: remove the text `content1`)
请确保页面上也包含jQuery脚本。如果不在jQuery中包装DOM元素,您将调用普通javascript函数。在javascript中,remove()
存在(用于从选择列表中删除一个选项),而empty()
不存在不,DOM API中没有empty()
方法,为什么您希望jQuery方法在非jQuery对象上工作?至于你声称它“永远不起作用”,我想你会发现它至少会产生一个错误。.empty()
是jQuery对象上的jQuery方法.remove()
是jQuery对象上的jQuery方法和节点上的DOM方法的名称。代码中没有使用jQuery。尝试$(目标[0]).empty()代码>。哦,谢谢,,,是因为我不能将JavaScript和jQuery对象混合使用吗?@CraziliaZettoMan认为jQuery是一个构建在JavaScript之上的库,它为您提供了额外的功能,让您的生活更轻松。如果您不使用jQuery,那么这些“方便的”功能将不适用于您。你必须自己去做。不知道为什么这被否决了,因为它直接回答了他的问题
var targets = document.getElementsByClassName('target');
$(targets[0]).remove(); //will remove the first element with class `target` from the DOM
$(targets[1]).empty(); //will empty the contents of the second element with class `target` in the DOM (i.e: remove the text `content1`)