![](/img/trans.png)
[英]Why would a function return undefined if you're not returning anything? Javascript
[英]Why would jQuery return undefined for the css function of an element?
jQuery 1.11.1,在 Mac OS X Mavericks 上,Safari 的最新版本。
我正在尝试使用 css 函数设置 CSS 属性。 元素中缺少 css()。
首先,我验证是否正确选择了元素:
// There is only one element that has id="container"
var $container = $('#container');
// Selector returns a collection. I have to access first element:
console.log($container[0]); // prints HTMLDivElement
// css function is undefined
console.log($container[0].css); // prints undefined
// Also can't set any css value. Gives undefined error.
$container[0].css({backgroundColor:'blue'});
错误是:
TypeError: 'undefined' 不是一个函数(评估 '$container[0].css({backgroundColor:'blue'})')
我从测试页中删除了所有内容。 它包含 jQuery,并且在正文中包含带有 ID 的 div。 很简单。 在它下面,是上面显示的 JavaScript 代码。
知道为什么 div 会缺少 css 功能吗?
这是因为您正在退出 jQuery 对象并使用 DOM 元素...
$container[0].css({backgroundColor:'blue'});
这里的[0]
从 jQuery 对象中获取 DOM 对象。
如果要访问 jQuery 方法,请使用 jQuery...
$container.css({backgroundColor:'blue'});
您错误地使用了 jQuery。 当您说$container[0]
您将获得 jQuery 对象的第一个 javascript DOM 元素(它没有附加任何 jquery 函数)。 如果你想使用 jQuery 获取元素的 css 背景颜色,你需要做$container.css("background-color")
,并设置它$container.css("background-color", "blue");
或$container.css({ "background-color": "blue" });
因为css
函数是一个jquery对象的方法。 当您执行$container[0]
您将获得与选择器匹配的第一个 DOM 节点,它不是 jquery 对象。
试试$container.css(...)
。
当您访问集合项时,不再有 jQuery 方法,只有 DOM 元素。
你可以替换:
$container[0].css({backgroundColor:'blue'});
经过
$container.css({backgroundColor:'blue'});
如果您还有一个具有相同 css 属性的 div 元素,
例如让我们说下面的语句返回多个结果:
var $container = $('.container'); // Has 3 results
并且您想访问特定元素的 css 属性,然后您可以将 dom 元素恢复为 jquery 元素并执行您想要的操作,如下所示:
$($('.container').get(2)).css({ "background-color": "blue" });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.