检测jQuery-selector是否被点击的最佳方法是什么?我的意思是:
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'))});
答案 0 :(得分:2)
尝试制作这个数组
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'))});
});
答案 1 :(得分:2)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" attrb="1,2" class="sizecheck" name="size">
<input type="checkbox" attrb="4,5" class="sizecheck" name="size">
<br/> check box active state
<li class="coloridchange" data-id="1">
<input type="checkbox" autocomplete="off" class="hidden" value="1" name="color">1</li>
<li class="coloridchange" data-id="2">
<input type="checkbox" autocomplete="off" class="hidden" value="2" name="color">2</li>
<li class="coloridchange" data-id="4">
<input type="checkbox" autocomplete="off" class="hidden" value="4" name="color">4</li>
<li class="coloridchange" data-id="5">
<input type="checkbox" autocomplete="off" class="hidden" value="5" name="color">5</li>
$(function() {
$(document).on('mouseenter', 'div[data-background]', function() {
$(this).css({'background' : 'url('+$(this).data('background')+')',});
});
});
div {
width : 500px;
height : 320px;
border : 1px solid #A2A2A2;
}
答案 2 :(得分:1)
仅适用于此情况。
由于您有单个类选择器,假设您没有多个类
$('.far','.foooo','.bar','.some').mouseenter(function(){
var selector = $(this).attr('class');
$(this).css('background-image',url(selector+'.png'));
});
答案 3 :(得分:-3)
你需要这样的东西:
$(".foo").click(function (event) {
$(this).css("color", "red");
});
同样,您需要点击,而不是mouseenter。因为mouseenter只是一个悬停,你可以使用普通的css。