我想提高脚本的性能,因此决定使用JavaScript each()
循环更改for
方法。我通过outerHeight()
方法收到控制台错误。
jQuery.Deferred异常:a.outerHeight不是函数TypeError:a.outerHeight不是函数
如何解决这个问题?
$(document).ready(function() {
var menuListElements = $('#mainMenuList').find("a.navigationLinks"), a;
for (var i = 0; i < menuListElements.length; ++i) {
a = menuListElements[i];
if (a.outerHeight() > 25) {
a.css({'color': "green"});
} else a.css({'color': "black"});
}
});
#mainMenuList {
display: flex;
flex-direction: column;
width: 110px;
text-align: center;
}
#mainMenuList a {
min-height: 25px;
border: 1px solid black;
background-color: lightgrey;
text-decoration: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainMenuList">
<a href="#" class="navigationLinks">Link 1</a>
<a href="#" class="navigationLinks">Link 2</a>
<a href="#" class="navigationLinks">Link 3 with more text</a>
<a href="#" class="navigationLinks">Link 4</a>
<a href="#" class="navigationLinks">Link 5 with more text</a>
<a href="#" class="navigationLinks">Link 6 with more text</a>
</div>
答案 0 :(得分:3)
问题在于a
变量包含一个 HTML 元素。您应该使用
jquery
对象
a = $(menuListElements[i]);
$(document).ready(function() {
var menuListElements = $('#mainMenuList').find("a.navigationLinks"), a;
for (var i = 0; i < menuListElements.length; i++) {
a = $(menuListElements[i]);
if (a.outerHeight() > 30) {
a.css({'color': "green"});
} else a.css({'color': "black"});
}
});
#mainMenuList {
display: flex;
flex-direction: column;
width: 110px;
text-align: center;
}
#mainMenuList a {
min-height: 25px;
border: 1px solid black;
background-color: lightgrey;
text-decoration: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainMenuList">
<a href="#" class="navigationLinks">Link 1</a>
<a href="#" class="navigationLinks">Link 2</a>
<a href="#" class="navigationLinks">Link 3 with more text</a>
<a href="#" class="navigationLinks">Link 4</a>
<a href="#" class="navigationLinks">Link 5 with more text</a>
<a href="#" class="navigationLinks">Link 6 with more text</a>
</div>