Не могу получить функцию с JQuery для работы - PullRequest
3 голосов
/ 21 июня 2011

Следующий код ниже работает нормально:

$("#searchTab").click(function(){
$(".tab").addClass("tabNo");
$(".tab").removeClass("tabYes");
$(this).addClass("tabYes");
$(".content").hide();
$("#searchContent").show();
});

, но если я пытаюсь организовать код в функцию, как показано ниже, она не работаетТолько "$ (". Content "). Hide ();"из функции вроде бы работают.Почему это?

function tabSelect(){
$(".tab").addClass("tabNo");
$(".tab").removeClass("tabYes");
$(this).addClass("tabYes");
$(".content").hide();
}

$("#searchTab").click(function(){
    tabSelect();
    $("#searchContent").show();
});

Ответы [ 2 ]

7 голосов
/ 21 июня 2011

Ссылка this изменилась. Вам нужно будет передать его в качестве аргумента tabSelect или обернуть его и использовать обертку. ($(this))

function tabSelect($itemToTab){
$(".tab").addClass("tabNo");
$(".tab").removeClass("tabYes");
$itemToTab.addClass("tabYes");
$(".content").hide();
}

$("#searchTab").click(function(){
    tabSelect($(this));
    $("#searchContent").show();
});
4 голосов
/ 21 июня 2011

Изменить это:

tabSelect();

к этому:

tabSelect.call( this );

Это вручную устанавливает значение this в контексте вызова tabSelect().

function tabSelect(){
    $(".tab").addClass("tabNo").removeClass("tabYes");  // chain these!
    $(this).addClass("tabYes");  // now "this" is the element you're expecting
    $(".content").hide();
}

$("#searchTab").click(function(){
    tabSelect.call( this ); // set "this" in the calling context of "tabSelect"
                            //   to the current value of "this" (the element)
    $("#searchContent").show();
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...