Sending a variable to another function
I have these 2 functions and would like 1 to execute the other with a specified variable:
function ckbmovestate() {
$(this).css("-webkit-transform", "translate(53px, 0px)")
};
function initcheckbox(){
var togglebox = "<div class='toggle_box'><div class='switch'></div></div>";
$('input[type=checkbox]').css('display','none');
$('fieldset[data-input-type=checkbox]').append(togglebox);
$('fieldset:has(:checkb开发者_开发百科ox:checked)').each(function(){
$(this).find('.switch').attr('data-state', 'on');
ckbmovestate($(this))
});
$('fieldset:has(:checkbox:checked)')
$('fieldset:not(:has(:checkbox:checked))').find('.switch').attr('data-state', 'off');
};
As you might guess, this does not work. Question is why? Could you give me a quick course on variable handling? Thanks guys, I know you are the best!
The simplest option is to define your function to take a parameter:
function ckbmovestate(element) {
$(element).css("-webkit-transform", "translate(53px, 0px)")
}
You can then call this with ckbmovestate(this)
from your code.
If you really want to be able to use the this
keyword within a function when it's called, you can do so. It's not worth it here, but there may come a time when you want to do this. To achieve this, you need to make use of call
or apply
. Here, either would work:
ckbmovestate.call(someElement);
This sends the value of someElement
to ckbmovestate
. Inside ckbmovestate
, you will be able to access the value using the keyword this
. So in you code above, the following call would work:
ckbmovestate.call(this);
This is almost certainly overcomplicating things for this situation, however -- much easier to define a parameter.
because you don't accept an argument in ckbmovestate
your ckbmovestate function should look like this if you don't want to change too much of your code:
function ckbmovestate(element){
element.css("-webkit-transform", "translate(53px, 0px)");
}
If you often use the ckbmovestate function, I suggest you make your own little plugin of it, which you do like this;
$.fn.ckbmovestate = function(){
$(this).each(function(){
$(this).css("-webkit-transform", "translate(53px, 0px)");
});
}
than, in the jquery each loop in your code in the question, you can write this:
$('fieldset:has(:checkbox:checked)').each(function(){
$(this).find('.switch').attr('data-state', 'on')
.ckbmovestate();
});
Change the function to use a parameter.
function ckbmovestate( x ) {
x.css("-webkit-transform", "translate(53px, 0px)")
};
精彩评论