我的 DOM 结构看起来像:
<div class="weather-Dashboard"></div>
Dashboard
<div class="weather-Charts">
charts
</div>
<div class="weather-Statistics">
Statistics
</div>
<div class="weather-Sites">
Sites
</div>
我想选择每个div
包含weather
类的 dom,并使用 jQuery 隐藏它们。下面是我的JS代码:
var e = $('div[class *= "weather"]');
e.each(function() {
console.log(this);
this.hide();
});
运行此代码后,我得到以下错误:
未捕获的类型错误:this.hide 不是一个函数
似乎this
不是jQuery对象。我的代码有什么问题?我已经尝试过,如果只有一个 DOM 与查询匹配,我可以调用e.hide()
来隐藏 dom。但是,当有多个 DOM 匹配时,它不起作用。
问题是因为this
指的是没有hide()
方法的 DOMElement。您需要先将this
包装在 jQuery 对象中:
var e = $('div[class*="weather"]');
e.each(function() {
$(this).hide();
});
但是,您应该注意,这里不需要each()
循环 - 您可以直接在集合上调用hide()
:
$('div[class*="weather"]').hide();
在each()
方法中,this
引用DOM对象,hide()
是一个jQuery方法,所以你需要将其转换为jQuery对象。
$(this).hide();
或者只是更新display
样式属性。
this.style.display = 'none';
<</div>
div class="one_answers">var e = $('div[class *= "weather"]');
e.each(function() {
$(this).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="weather-Dashboard"></div>
Dashboard
<div class="weather-Charts">
charts
</div>
<div class="weather-Statistics">
Statistics
</div>
<div class="weather-Sites">
Sites
</div>