选择标题以字符串开头且具有特定类的元素

时间:2019-04-01 15:25:46

标签: jquery class selector title

我想选择具有特定类的项目,并且其标题以特定字符串开头。以下内容对我不起作用-选择了仅符合条件之一的元素。如何指定两者必须匹配?

var $elementsIWant = $('.hoverClass, div[title^="Click here"]');

$elementsIWant.mouseenter(function () {
  $('.box').css({
    'background-color': 'red'
  })
});

$elementsIWant.mouseleave(function () {
  $('.box').css({
    'background-color': 'white'
  })
});
.box {
  border: 1px solid black;
  width: 100px;
  height: 100px;
  background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div title="Click here for more information" class="hoverClass">
  Hovering over this element should change the box red
</div>
<br>
<br>
<div title="Fake title" class="hoverClass">
  Hovering over this element shouldn't change the box
</div>
<br>
<br>
<div title="Click here for more information" class="fakeClass">
  Hovering over this element shouldn't change the box
</div>
<br>
<br>
<div class="box">
</div>

非常感谢。

1 个答案:

答案 0 :(得分:1)

您正在使用两个不同的选择器。匹配的任何一个都将被选择。您需要将它们结合起来:

var $elementsIWant = $('div.hoverClass[title^="Click here"]');

请参阅以下演示:

var $elementsIWant = $('div.hoverClass[title^="Click here"]');

$elementsIWant.mouseenter(function () {
  $('.box').css({
    'background-color': 'red'
  })
});

$elementsIWant.mouseleave(function () {
  $('.box').css({
    'background-color': 'white'
  })
});
.box {
  border: 1px solid black;
  width: 100px;
  height: 100px;
  background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div title="Click here for more information" class="hoverClass">
  Hovering over this element should change the box red
</div>
<br>
<br>
<div title="Fake title" class="hoverClass">
  Hovering over this element shouldn't change the box
</div>
<br>
<br>
<div title="Click here for more information" class="fakeClass">
  Hovering over this element shouldn't change the box
</div>
<br>
<br>
<div class="box">
</div>