문제

어떻게 새 div 태그를 추가하십시오 확인란을 확인할 때 확인란 옆에 있고 두 개의 확인란을 확인하면 두 개의 div 태그가 표시되어야합니다. jQuery를 사용 하여이 모듈을 해결하도록 도와주세요.

도움이 되었습니까?

해결책

$(':checkbox').click(function () {
    if ($(this).attr('checked')) {
        // create new div
        var newDiv = $('<div>contents</div>');

        // you can insert element like this:
        newDiv.insertAfter($(this));

        // or like that (choose syntax that you prefer):
        $(this).after(newDiv);
    } else {
        // this will remove div next to current element if it's present
        $(this).next().filter('div').remove();
    }
});

Checkbox '레이블 옆 에이 새 Div를 추가하지 않으려면 먼저 확인란에 대한 ID 설정과 해당 레이블에서 레이블에 레이블을 사용하여 확인란을 사용하는지 확인하십시오.

<label for="myCb1">test</label>
<input type="checkbox" id="myCb1" value="1" />

이제 JS 코드를 조금 이상 수정하면 다음과 같습니다.

$(':checkbox').click(function () {
    // current checkbox id
    var id = $(this).attr('id');

    // checkbox' label
    var label = $('label[for=' + id + ']');

    if ($(this).attr('checked')) {
        // create new div
        var newDiv = $('<div>contents</div>');

        // insert div element
        newDiv.insertAfter(label);
    } else {
        // this will remove div next to current element if it's present
        label.next().filter('div').remove();
    }
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top