在鼠标回车时检查元素的内容
checking a element's content on mouse enter
我正在尝试设置一个鼠标输入事件,如果元素包含某个文本,它会触发该事件,但由于某种原因它无法识别 :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")
}
}
});
相关文章:
- 在单击任何位置时隐藏元素,而不检查每次DOM单击
- 用于检查数组中是否存在元素的javascript自定义方法
- 检查元素是如何获得焦点的
- 如何检查元素的内容是否为空,如果为空,请在jquery中删除该元素
- 在验证器中添加自定义规则以检查<ul>具有元素
- 如何检查元素是否在iframe中
- 使用 jQuery 检查元素的数量
- 使用js/jQuery检查对象(而不是元素)是否真的存在
- 检查元素是否将状态从隐藏更改为可见
- 我如何为列出的选项卡元素编写一个Protractor测试,它会检查它是否's是否处于活动状态
- JS触发器值检查在文档加载后添加到页面的元素在加载时更改AND
- 如何设置第一个子元素's的单选按钮已在轨道上检查4
- 检查元素hasClass是否添加了AJAX
- 如何根据数组中的元素检查字符串
- jQuery根据类中的其他元素检查每个元素
- Javascript合并两个函数,用另一个元素检查节点类型
- 不能得到ajax得到显示在页面,但可以看到在谷歌元素检查器
- 使用inspect元素检查是否修改了代码
- 模拟webkit的元素检查器
- 如何使用元素检查器在网站上运行我自己的事件处理Javascript代码