我有一些我在这里找到的JavaScript,但我似乎无法让它工作.
我有一个id为'latest'的h1,如果少于21个字符,它应该有pt45类.
// The number of characters
var yourElement = $('h1.latest');
var charLength = yourElement.text().length;
if(charLength < 20){
yourElement.addClass('pt45');
}Run Code Online (Sandbox Code Playgroud)
.pt45 {
font-size: 10px;
color:red;
}Run Code Online (Sandbox Code Playgroud)
<h1 class="latest">123456789</h1>
<h1 class="latest">123456789123456789123456789123456789</h1>Run Code Online (Sandbox Code Playgroud)
var yourElement = $('h1.latest');
Run Code Online (Sandbox Code Playgroud)
这将返回一个包含匹配NodeList的jQuery对象.
yourElement.text().length; 当你有两个h1时会给两个
相反,它必须是:
jQuery("h1.latest").each(function() {
if(jQuery(this).text().length < 21 ) {
jQuery(this).addClass("pt45")
}
});Run Code Online (Sandbox Code Playgroud)
.pt45 {
font-size: 10px;
color:red;
}Run Code Online (Sandbox Code Playgroud)
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<h1 class="latest">123456789</h1>
<h1 class="latest">123456789123456789123456789123456789</h1>Run Code Online (Sandbox Code Playgroud)
您必须迭代Nodelist并检查长度