在鼠标回车时检查元素的内容

checking a element's content on mouse enter

本文关键字:元素 检查 鼠标 回车      更新时间:2023-09-26

我正在尝试设置一个鼠标输入事件,如果元素包含某个文本,它会触发该事件,但由于某种原因它无法识别 :contains 参数。

.html:

<div class="sample">red</div>
<div class="sample">text</div>

JavaScript:

$(".sample").on({
    mouseenter: function () {
    if($("this:contains('red')").length > 0)
   { $(this).css("background-color","red")}
    },
    mouseleave: function () {
     if($("this:contains('red')").length > 0){
        $(this).css("background-color","yellow")}
    }
});

这是JSFiddle

任何帮助将不胜感激!

就个人而言,我会检查div .text()的值。 您的选择器已关闭,因为您没有选择 JS this,而是选择字符串"this"。

$(".sample").on({
    mouseenter: function () {
    if($(this).text() =='Red') { 
      $(this).css("background-color","red")}
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sample">Red</div>
<div class="sample">Text</div>

使用 is :-

$(".sample").on({
  mouseenter: function() {
    if ($(this).is(":contains('red')")) {
      $(this).css("background-color", "red")
    }
  },
  mouseleave: function() {
    if ($(this).is(":contains('red')")) {
      $(this).css("background-color", "yellow")
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sample">red</div>
<div class="sample">text</div>

试试这个

$(".sample").on({
  mouseenter: function() {
    if ($(this).is(":contains('red')")) {
      $(this).css("background-color", "red")
  }
},
mouseleave: function() {
    if ($(this).is(":contains('red')")) {
      $(this).css("background-color", "yellow")
   }
  }
});

"这"不应该用引号引起来

使用 jQuery .text()

$(".sample").on({
mouseenter: function () {
if($(this).text()=="red")
{ 
  $(this).css("background-color","red")}
},
mouseleave: function () {
 if($(this).text()=="red"){
    $(this).css("background-color","yellow")}
}
});`

而不是使用复杂的:

if($("this:contains('red')").length > 0)

尝试更简单的方法:

if(this.innerHTML === 'red')

它工作正常。您还可以使用:

if(this.textContent === 'red')

测试了这种方式,它有效。

我不确定如何让包含在这种语句中工作 - 我有一种感觉,这与你正在检查元素而不是文本有关,请尝试使用它:

$(function(){
$(".sample").on({
  mouseenter: function () {
    if(this.innerHTML.indexOf("red") != -1){
       $(this).css("background-color","red")
     }
  },
  mouseleave: function () {
    if(this.innerHTML.indexOf("red") != -1){
      $(this).css("background-color","yellow")
    }
  }
});