jQuery.contains()无法正常工作 [英] jQuery.contains() does not work properly
问题描述
在下列情况下我应该得到警告,但我没有得到任何警报。我正在尝试一个简单的例子 jQuery.Contains()
。
I should get an "alert" in the following case, but I am not getting any "alert". I am trying a simple example of jQuery.Contains()
.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
var alpha = $.contains('body','p') {
alert(alpha);
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
推荐答案
根据jQuery 文档 API只接受元素节点(不是JavaScript / jQuery 对象或选择器)
As per the jQuery documentation the API takes only element nodes (not JavaScript/jQuery objects or selectors)
检查 DOM元素是否是另一个 DOM元素的后代。
仅支持元素节点;如果第二个参数是文本或
注释节点,$ .contains()将返回false。
Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.
注意:第一个参数必须是DOM元素,而不是jQuery对象或纯JavaScript对象。
Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.
您应该将代码更改为
$(function () {
alert($.contains(document.body, $("p")[0])) //alerts true
alert($.contains(document.body, document.getElementsByTagName("p")[0])); //alerts true
})
这篇关于jQuery.contains()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!