How to make array in function with options to run. This is declaration:
$(".object").myfunction({
run1: 'spell',
run2: true
});
Here is function:
$.fn.myfunction= function() {
alert(run1);
};
How to alert the run1 or run2 from declaration ?
-
Why would you want to do that? why are you adding functionality to the base jQuery object if the functionality doesn't use the object?Amit– Amit2016年01月16日 21:12:21 +00:00Commented Jan 16, 2016 at 21:12
-
@Amit That is only example, I am building sth more :)Mergars– Mergars2016年01月16日 22:52:10 +00:00Commented Jan 16, 2016 at 22:52
2 Answers 2
Add an object for the function to receive
$.fn.myfunction= function(params) {
alert(params.run1);
};
answered Jan 16, 2016 at 20:38
JNF
3,7403 gold badges35 silver badges65 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
JNF
@Mergars, is the function declaration before or after the invocation?
Mergars
Can you tell me, how spell function without params or with params (2 functions on 1 page) It's desn't works with your result.
JNF
javascript cannot overload functions in the way you are suggesting. If you try - only the last will work. What you can do - is check what you have received, i.e.
if (params === undefined){/*code for no params*/}else{/*code with params*/}My proposal is:
$.fn.myfunction= function(obj, key) {
alert(obj[key]);
/*****
$.each(obj, function(index, element) {
alert("Key: " + index + " Value: " + element);
});
*****/
};
$(function () {
$(".object").myfunction({
run1: 'spell',
run2: true
}, 'run1');
});
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<button class="object" style="visibility:hidden">Click Me</button>
answered Jan 16, 2016 at 20:42
gaetanoM
42.1k6 gold badges45 silver badges63 bronze badges
lang-js