Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何检测选择器是否单击?_Javascript_Jquery - Fatal编程技术网

Javascript 如何检测选择器是否单击?

Javascript 如何检测选择器是否单击?,javascript,jquery,Javascript,Jquery,检测jQuery选择器是否单击的最佳方法是什么。我的意思是: var elem = 'foo' var action = $(elem ).mouseenter(function(){ $(this).css('background-image',url(elem +'.png')) }); var elem = 'bar' //do the same action with new elem var elem = 'blah' //do the same action with new ele

检测jQuery选择器是否单击的最佳方法是什么。我的意思是:

var elem = 'foo'
var action = $(elem ).mouseenter(function(){
$(this).css('background-image',url(elem +'.png'))
});
var elem = 'bar'
//do the same action with new elem
var elem = 'blah'
//do the same action with new elem
问题是如何将此代码缩短为一行:

$('.far').mouseenter(function(){$(this).css('background-image',url(far.png'))});
$('.foooo').mouseenter(function(){$(this).css('background-image',url(foooo.png'))});
$('.bar').mouseenter(function(){$(this).css('background-image',url(bar.png'))});
$('.some').mouseenter(function(){$(this).css('background-image',url(some.png'))});
尝试制作此数组

var arr = [ "far", "foooo", "bar", "some" ];
arr.forEach( function( item ){
    $('.' + item ).mouseenter(function(){$(this).css('background-image','url('+ item +'.png'))});
    //adding the click detection as well
    $('.' + item ).click(function(){$(this).css('background-image','url('+ item +'.png'))});
});

只有在这种情况下才有效

因为您只有一个类选择器,假设您没有多个类

$('.far','.foooo','.bar','.some').mouseenter(function(){
 var selector = $(this).attr('class');
 $(this).css('background-image',url(selector+'.png'));
});
$(函数(){
$(文档).on('mouseenter','div[数据背景]',function(){
$(this.css({'background':'url(+$(this.data('background')+'),});
});
});
div{
宽度:500px;
高度:320px;
边框:1px实心#A2A2;
}

您需要这样的东西:

$(".foo").click(function (event) {
    $(this).css("color", "red");
});

同样,您需要的是单击,而不是鼠标。因为mouseenter只是一个悬停,你可以用普通的css来实现。

你的问题“我如何检测选择器是否点击?”或者“我如何将此代码缩短为一行:”??你想点击
事件
或者
mouseenter
?如果点击了div,则不会检测到。这只是一个简单的例子hover@alpham8Op不需要点击检测。无论如何,如果OP想要,他可以简单地用click替换mouseenter。同上。只是一个悬停,而不是点击detection@alpham8添加了点击检测,但是OP的问题不是这个。仔细阅读这个问题。同时,帮助别人时让别人泄气也不是一件值得感激的事情。对这个答案投了赞成票。问题标题是关于这个的。@ANS也谢谢你+1。Alpham8-您需要仔细阅读整个问题。也不要单击detecting@alpham8你所说的点击是什么意思?OP裁判点击作为事件的示例。他的意思是在鼠标上方检测选择器。@Mohammad同意你的意见Mohammad。在我的答案的第一行,同样的指向OP:)-1。您必须理解OP想要让selected elements类重构他/她的代码这一点。与事件毫无关系