Overview
I am trying to find a jQuery function that matches the value of a selection attribute and runs that function on selection.
Example.
$('[data-store="' + key + '"]').each(function() {
var $callback = $(this).attr('data-filter');
if($callback != null) {
var fn = window['$.fn.nl2br()'];
if(jQuery.isFunction(fn)) {
$(this).fn();
}
}
$(this).setValue(value);
});
Problem 1
I am not sure how to create a jQuery function call from a string.
I know that I can call a function like this, $ (this) 'onclick'; however, I canβt check if it exists before trying to call it.
Normally I could do this: var strfun = 'onclick'; var fn = body [strfun];
if(typeof fn === 'function') {
fn();
}
This seems like an error:
var fn = window['$.fn.nl2br()'];
if(jQuery.isFunction(fn)) {
$(this).fn();
}
EDIT:
I seem to have been successful:
if($callback != null) {
var fn = $(this)[$callback]();
if( typeof fn === 'function') {
$(this)[$callback]();
}
}
Problem 2
Using jQuery.isFunction () how to check if methods exist? can you do this with jQuery.isFunction ()?
Example
Declare a function:
$.fn.nl2br = function() {
return this.each(function() {
$(this).val().replace(/(<br>)|(<br \/>)|(<p>)|(<\/p>)/g, "\r\n");
});
};
Check if the function exists, these parameters do not work:
jQuery.isFunction($.fn.nl2br); // = false
jQuery.isFunction($.fn['nl2br']()); //false
source
share