문제

나는 이것을 짧게 유지하려고 노력할 것입니다.사용자가 확장 버튼을 클릭하면 숨기거나 표시되는 텍스트 상자를 만들려고 합니다.저는 Toggle() 메소드를 사용하고 있습니다.

마크업은 다음과 같습니다.

<span id="toggle0">+</span>
<div id="toggle0Container">
    blablabla...
<div>

<span id="toggle1">+</span>
<div id="toggle1Container">
    blablabla...
<div>

<span id="toggle2">+</span>
<div id="toggle2Container">
    blablabla...
<div>

// etc

#toggle0은 #toggle0Container를 토글하고, #toggle1은 #toggle1Container를 토글합니다.이는 모두 PHP에 의해 생성되므로 이러한 컨테이너는 얼마든지 있을 수 있습니다.

JQuery 코드는 다음과 같습니다.

$(document).ready(function() {
    // array of numbers, it's pretty redundant, there will never be more than 30 containers
    var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9 , 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36];
    // hide all containers first
    jQuery.each(arr, function() {
        $('#toggle' + this + 'Container').hide();
    });
    // now the toggle buttons
    jQuery.each(arr, function() {
        $('#toggle' + this).click(function() {
            // this line is not working
            $('#toggle' + this + 'Container').slideToggle('slow');
            // and this just changes the toggle button from + to -
            if ($(this).html() == '+') {
                $(this).html('-');
            } else {
                $(this).html('+');
            }
        });
    });
});

토글 부분을 제외하고는 작동합니다(작동하지 않는 줄 위에 설명을 추가했습니다).문제가 어디에 있나요?

도움이 되었습니까?

해결책

나는 mgroves의 접근 방식을 따를 것이지만, 당신이 정말로 배열을하고 싶거나, 각 ()를 올바르게 사용하는 방법을 알아 내고 싶다면 다음과 같은 방법은 다음과 같습니다.

$(document).ready(function() {
    // array of numbers, it's pretty redundant, there will never be more than 30 containers
    var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9 , 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36];
    // hide all containers first
    jQuery.each(arr, function(index, item) {
        $('#toggle' + item + 'Container').hide();
    });
    // now the toggle buttons
    jQuery.each(arr, function(index, item) {
        $('#toggle' + item).click(function() {
            // this line is not working
            $('#toggle' + item + 'Container').slideToggle('slow');
            // and this just changes the toggle button from + to -
            if ($(this).html() == '+') {
                $(this).html('-');
            } else {
                $(this).html('+');
            }
        });
    });
});

다른 팁

"this"는 이제 다른 범위에 있으며 배열의 숫자 중 하나가 아니라 실제 #TogGlen dom 요소를 참조하기 때문입니다.

숫자 배열을 버리고 다른 선택기를 사용하는 것이 좋습니다.


$("div[id^=toggle][id$=container]").hide();

$("span[id^=toggle]").click(function() {
     $(this).find("span[id^=toggle][id$=container]").slideToggle("slow");
     // .. do your other html stuff
}

각각을 버리고 토글 선택기를 그로 바꾸십시오.

편집하다

나는 당신의 특정 사용 사례에 대해 mgroves 솔루션을 더 좋아하지만, 나는 당신이 .Each 메소드의 매개 변수로 인덱스와 요소를 어떻게 받아 들일 수 있는지 설명하는 내 답을 남겨 두겠습니다.

원래 답변

다른 사람들이 말했듯이 이것 당신이 그것을 언급하는 시점에 있다고 생각하는 것이 아닙니다. 다음은 Remy Sharp의 훌륭한 기사입니다.jQuery는 이것입니다 : Demystified"나는 당신이 읽는 것이 좋습니다.

.Each 함수는 당신을 크게 도울 수있는 두 개의 매개 변수를 허용 할 수 있으며 해당 숫자 배열이 필요하지 않습니다.

$('span[id^=toggle']').each(function(idx, elem) {

    // idx is the current index of the jQuery object
    $('#toggle' + idx).click(function() {

        // elem is the current element
        $(elem).next('#toggle' + idx + 'Container').slideToggle('slow');

        if ($(elem).html() == '+') {
            $(elem).html('-');
        } else {
            $(elem).html('+');
        }

    });

});

"Toggler"와 같은 토글 버튼 (SPAN) 및 "컨테이너"와 같은 토글 컨테이너 또는 JavaScript를 단순화하기 위해 수업을 배치하는 것이 좋습니다.

$(function() {
    // hide all containers first
    $(".container").hide();
    // now the toggle buttons
    $(".toggler").click(function() {
          var container = $("#" + $(this).attr("id") + "Container");
          container.slideToggle("slow");

          $(this).html(container.is(":visible") ? "-" : "+");
    });
});

그 사진을 줘.

Mgroves가 말했듯이, 각 ()를 사용하여 범위가 모두 멈추고 있습니다. 보다 이것 자세한 내용은.

나는 맥스가 수업을 사용하는 것에 대해 정확히 무엇을했는지 정확히 게시하려고했다. 나는이 더 쉬운 선택기로 그의 제안을 컨테이너를 찾는 것만 향상시킬 것입니다.

$(function() {
  // hide all containers first
  $(".container").hide();
  // now the toggle buttons
  $(".toggler").click(function() {
    $(this).next().slideToggle("slow");

    if (container.is(":visible")) {
      $(this).html("-");
    }
    else {
      $(this).html("+");
    }
  });
});

스팬에서 클래스를 쉽게 얻을 수없는 경우 $ ( '#spancontainer> span')와 같은 것을 사용하여 비슷한 선택기를 만들어 태그 이름으로 선택하여 포함 요소에서 내려갈 수 있습니다.

당신은 당신의 요소를 검색 할 수있는 수업을 제공하고, 다음을 이용해야합니다. next.

마크 업을 다음과 같이 만드십시오.

<span class="toggleButton">+</span>
<div class="toggleContainer">
   blablabla...
<div>

이제 이것을 처리하는 코드는 다음과 같이 간단 해집니다.

$('.toggleButton').click(function() {
    $(this).next('.toggleContainer').slideToggle('slow');
});

나는 최근에 이와 같은 행동을 위한 상당히 실질적인 스크립트를 작성했습니다.나는 포함 div에서 주어진 숨기기/표시 요소의 모든 요소를 ​​래핑하기로 선택했다는 점에서 약간 다른 경로를 선택했습니다.필요한 경우 한 섹션에 대해 여러 개의 "트리거"를 가질 수 있으며 번호 매기기에 대해 걱정하지 않고 임의의 수의 숨기기/표시 요소를 추가할 수 있습니다.나는 그것을 다음과 같이 구성할 것이다:

<div class="expSecWrapper">
    <div class="expSecTrigger">Insert Trigger Here</div>
    <div class="expSecBody">
        Content to hide/show
    </div>
</div>

그러면 jQuery 코드는 다음과 같습니다.

$(document).ready(function(){
    var targets = $(".expSecWrapper")
    targets.find(".expSecTrigger").click(function(){
        targets.find(".expSecBody").hide()
        $(this).parents(".expSecWrapper").eq(0).children(".expSecBody").toggle();
    })
})

애플리케이션에 나머지 관련 JS를 추가할 수 있습니다.

hide/show 본문이 래퍼의 직계 자손이어야 하는 필요성과 같은 몇 가지 제한 사항이 있습니다.드롭다운, 라디오 버튼 등에 적용할 수 있습니다.또한 중첩 가능하므로 숨기거나 표시하는 경우 여러 수준을 가질 수 있습니다.

마지막으로 해당 동작을 할당하기 위해 실제로 .each 반복자를 사용할 필요조차 없다는 것입니다..click()과 같은 기능은 전체 jQuery 객체 그룹에 동작을 할당합니다.모든 대상을 포착하는 선택기를 사용하는 한.

죄송합니다. 몇 번 수정해야 했습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top