Javascript-форум (https://javascript.ru/forum/)
-   jQuery (https://javascript.ru/forum/jquery/)
-   -   Передать this в function (https://javascript.ru/forum/jquery/9248-peredat-v-function.html)

exvion 06.05.2010 12:18

Передать this в function
 
Пробую избавиться от дублирющихся кусков кода.
Вот исходник.
$(":checkbox").change(
	function () {
	if ($(this).attr('checked'))
		{
			$(this).closest("div").removeClass("checkboxOff");
			$(this).closest("div").addClass("checkboxOn");
			$(this).next("label").css('color','#FFFFFF');
		}
		else 
		{	
			$(this).closest("div").removeClass("checkboxOn");
			$(this).closest("div").addClass("checkboxOff");
			$(this).next("label").css('color','#000000');
		}
	});

$(":checkbox").click(
	function() {
	if ($(this).attr('checked'))
		{
			$(this).closest("div").removeClass("checkboxOff");
			$(this).closest("div").addClass("checkboxOn");
			$(this).next("label").css('color','#FFFFFF');
		}
		else 
		{	
			$(this).closest("div").removeClass("checkboxOn");
			$(this).closest("div").addClass("checkboxOff");
			$(this).next("label").css('color','#000000');
		}
	});


Как передать this в функцию?
somefunc=function(){
	if ($(this).attr('checked'))
		{
			$(this).closest("div").removeClass("checkboxOff");
			$(this).closest("div").addClass("checkboxOn");
			$(this).next("label").css('color','#FFFFFF');
		}
		else 
		{	
			$(this).closest("div").removeClass("checkboxOn");
			$(this).closest("div").addClass("checkboxOff");
			$(this).next("label").css('color','#000000');
		}

$(":checkbox").click(somefunc($(this)));
$(":checkbox").change(somefunc($(this)));

Kolyaj 06.05.2010 12:26

Цитата:

Сообщение от exvion
Как передать this в функцию?

http://javascript.ru/tutorial/object...ord#apply-call

micscr 06.05.2010 12:29

somefunc=function($this){
    if ($this.attr('checked'))
        {
            $this.closest("div").removeClass("checkboxOff");
...
$(":checkbox").click(function(){somefunc($(this));});

exvion 06.05.2010 13:01

Kolyaj.
Отправился читать. Спасибо за ссылку.
micscr
Как всегда оперативно и по делу. Огромное спасибо.


Часовой пояс GMT +3, время: 01:47.