如何在 if 语句中使用 .length 对象计数的答案?

How do I use the answer of an .length object count in an if statement?

我想在我的创作中有一些动态,因此需要 jQuery 计算 div 在不同的 div 中出现的次数,并根据答案执行一个函数;准确地说 css。

<div class="tiles">
  <div class="tile"></div>
  <div class="tile"></div>
  <div class="tile"></div>
</div> 

我要jQuery告诉我.tiles

.tile的数量
$(function() {
    var countOfTiles = $('.tiles > .tile').length;

    if ($('.tiles > .tile').length = 2) {
        alert('no');
    } else if ($('.tiles > .tile').length = 3) {
        alert('yes');
}

但是,它要么显示 'unexpected identifier',要么第一个语句始终为真..

那怎么办?

您需要使用 == 进行比较。您当前的代码正在尝试设置只读的长度 属性,因此出现错误

正确的代码是:

 $(function() {
     var countOfTiles = $('.tiles > .tile').length;

    if ($('.tiles > .tile').length == 2) {
        alert('no');
    } else if ($('.tiles > .tile').length == 3) {
      alert('yes');
}

单=是赋值,==是比较