我试图让 jquery 随机化,如果需要单击或双击来运行某些功能,但不知何故,我陷入了我尝试过的各种方式中。我知道不应该这样做,但我正在研究干扰。 :D
这是我的 atm 代码:
var rnd=Math.floor(Math.random()*2)
if(rnd != 0) {
$('.energie div.article').click(function() {
$('#maincontent').css('height', '100%');
$('.energie div.article').hide(),
$(this).next('div.detail').show();
$('#numbersenergie div').removeClass();
});
};
else {
$('.energie div.article').dblclick(function() {
$('#maincontent').css('height', '100%');
$('.energie div.article').hide(),
$(this).next('div.detail').show();
$('#numbersenergie div').removeClass();
});
};
};
最佳答案
//No more code redundancy - use a function :)
function handler() {
$('#maincontent').css('height', '100%');
$('.energie div.article').hide();
$(this).next('div.detail').show();
$('#numbersenergie div').removeClass();
//"reroll" the handler
bind();
}
//bind your event handler here, "50/50 probability"
function bind() {
//random whether it will be dblclick or click
var whatHandler = Math.random() > 0.5 ? 'dblclick' :'click';
//bind our handlers to a namespace called 'test' for easy unbinding
$('div').unbind('.test').bind(whatHandler + '.test', handler);
}
$(function() {
//on doc ready, bind our handler for the first time
bind();
});
请参阅此处的简化版本: http://jsfiddle.net/FvScr/10/
关于jquery - 随机化 .click 和 .dblclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6200737/