我将this question的答案转换为jQuery插件,但我正在努力解决问题。我在.on()中使用变量作为事件,但是侦听器永远不会触发。
jQuery
(function ($) {
$.fn.randomLetterStyles = function( options ) {
var settings = $.extend({
colors: ["#ddd", "#333", "#999", "#bbb"],
sizes:["12"],
type:"hover",
defaultColor: "#999",
defaultSize: "12"
}, options );
//both of these appear in console
console.log("check 1");
console.log(settings.type);
$(this).on(settings.type, function() {
//this does not appear in console
console.log("check 2");
wrapLetters(this);
$('.random-styles', this).css('color', function(){
var idx = Math.floor(Math.random() * settings.colors.length);
return settings.colors[idx];
});
$('.random-styles', this).css('color', function(){
var idx = Math.floor(Math.random() * settings.sizes.length);
return settings.sizes[idx];
});
$('.random-styles', this).css('font-size', function(){
var idx = Math.floor(Math.random() * settings.sizes.length);
return settings.sizes[idx];
});
}, function(){
$('.random-styles', this).css({'color':settings.defaultColor, 'font-size':settings.defaultSize});
});
};
//Recursive function by Logan Smyth
// Wrap every letter in a <span> with .random-color class.
function wrapLetters(el){
if ($(el).hasClass('random-styles')) return;
// Go through children, need to make it an array because we modify
// childNodes inside the loop and things get confused by that.
$.each($.makeArray(el.childNodes), function(i, node){
// Recursively wrap things that aren't text.
if (node.nodeType !== Node.TEXT_NODE) return wrapLetters(node);
// Create new spans for every letter.
$.each(node.data, function(j, letter){
var span = $('<span class="random-styles">').text(letter);
node.parentElement.insertBefore(span[0], node);
});
// Remove old non-wrapped text.
node.parentElement.removeChild(node);
});
}
} ( jQuery ));
$(document).ready(function() {
$("#firstBox").randomLetterStyles();
$("#secondBox").randomLetterStyles();
$("#thirdBox").randomLetterStyles();
});
HTML
<div id="firstBox">This box works on hover!</div>
<div id="secondBox">This box works on click!</div>
<div id="thirdBox">This box has custom settings!</div>
答案 0 :(得分:2)
.on('hover', function)
与.hover(function, function)
不同 - 它不接受两个函数。删除第二个和事件触发器。
您仍然可以创建这两个事件
$("#firstBox").randomLetterStyles({type: 'mouseover', ...}).randomLetterStyles({type: 'mouseout', ...});
答案 1 :(得分:1)
您不能在编写on()
语法时使用hover
方法。正确的方法是:
$(this).hover(function() {}, function() {});
这意味着您必须手动检查有效的事件类型,并相应地处理它们。