jQuery将CSS应用于具有ID X的所有元素



我的目标是将CSS应用于所有包含多个数字的p元素,例如:

<p id="winddir_text" >5 </p>    <!-- don't apply css -->
<p id="winddir_text"> 12 </p>   <!-- apply css -->
<p id="winddir_text"> 48 </p>   <!-- apply css -->

我的jQuery代码:

$(document).ready(function(){
var pString = $("#winddir_text").text();
var pLength = (pString).length;
if (pLength > 1)
    $("#winddir_text").css({"top": "33px", "left": "32px", "font-size": "30px"});
});

此代码仅将CSS应用于具有ID winddir_text的第一个元素。有人对如何解决此问题有任何想法吗?

在这种情况下,您应该使用类代替ID。

<p class="winddir_text" >5 </p>    <!-- don't apply css -->
<p class="winddir_text"> 12 </p>   <!-- apply css -->
<p class="winddir_text"> 48 </p>   <!-- apply css -->

然后使用每个循环目标类。

$(".winddir_text").each(function(){
  var pString = $(this).text();
  var pLength = (pString).length;
  if (pLength > 1)
    $(this).css({"top": "33px", "left": "32px", "font-size": "30px"});
  }
});

尝试以下代码,然后将类用作处理程序而不是ID。

$('p').each(function(){
    if( parseInt($(this).text()) > 9) {
    // $(this).css();
   }
});

您需要将这些ID更改为类

$(document).ready(function() {
  var ps = $(".winddir_text");
  $(ps).each(function() {
    var len = $(this).text().trim().length;
    if (len > 1) {
      $(this).css({
        top: "33px",
        left: "32px",
        "font-size": "30px"
      });
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="winddir_text" >5 </p>    <!-- don't apply css -->
<p class="winddir_text"> 12 </p>   <!-- apply css -->
<p class="winddir_text"> 48 </p>   <!-- apply css -->

您需要在页面上找到所有p元素,并通过它们全部介绍。jQuery为此提供了一个功能:$.each

$('p').each(function() {
  var length = $(this).text().trim().length;
  if (length > 1) {
    $("#winddir_text").css({"top": "33px", "left": "32px", "font-size": "30px"});
  }
});

这只会影响第一个#windir_text,因为您使用的是ID而不是类似类。您可以轻松更改这些和选择器以获得所需的结果。

最新更新