您好。
当我使用代码:
$(this).children('.test')[0].css('display','none');
我得到错误Uncaught TypeError: Cannot call method 'css' of undefined
为什么我会出错,怎么写对了?
您可能需要使用eq(0),因为[0]
返回纯DOM元素,并且上面没有css
方法。
$(this).children('.test').eq(0).css('display','none'); //or .hide()
或
$(this).children('.test:eq(0)').css('display','none');//or .hide()
或
$(this).children('.test')[0].style.display = 'none';
此外,您的错误意味着它可以是任何.test
,它们是上下文的子级[由于选择器没有返回任何内容,您正在未定义上访问css方法]。注意,子代只会查找直系后代,如果您想深入查找,可以使用find
。如果您的选择通过并返回了元素,那么您的代码将返回[element] has no method css
。上面使用jquery的片段(前2个)将抑制这些错误。
或
$(this).children('.test').eq(0).hide()