홈>
부트 스트랩 js와 css를 사용하여 Java 스크립트 확인란 트리에서 동적으로 만들었습니다. 선택 및 선택 취소가 작동하지 않음 : 여기에 이미지 설명 입력
두 번째 그림은 js에서 동적으로 생성 된 HTML입니다. 여기에 이미지 설명 입력 이것을 복사하고 html로 만들면 작동합니다. 동적으로 확인란 트리를 만드는 방법은 무엇입니까?
$(function() {
$('input[type="checkbox"]').change(checkboxChanged);
function checkboxChanged() {
var $this = $(this),
checked = $this.prop("checked"),
container = $this.parent(),
siblings = container.siblings();
container.find('input[type="checkbox"]')
.prop({
indeterminate: false,
checked: checked
})
.siblings('label')
.removeClass('custom-checked custom-unchecked custom-indeterminate')
.addClass(checked ? 'custom-checked' : 'custom-unchecked');
checkSiblings(container, checked);
}
function checkSiblings($el, checked) {
var parent = $el.parent().parent(),
all = true,
indeterminate = false;
$el.siblings().each(function() {
return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked);
});
if (all && checked) {
parent.children('input[type="checkbox"]')
.prop({
indeterminate: false,
checked: checked
})
.siblings('label')
.removeClass('custom-checked custom-unchecked custom-indeterminate')
.addClass(checked ? 'custom-checked' : 'custom-unchecked');
checkSiblings(parent, checked);
}
else if (all && !checked) {
indeterminate = parent.find('input[type="checkbox"]:checked').length > 0;
parent.children('input[type="checkbox"]')
.prop("checked", checked)
.prop("indeterminate", indeterminate)
.siblings('label')
.removeClass('custom-checked custom-unchecked custom-indeterminate')
.addClass(indeterminate ? 'custom-indeterminate' : (checked ? 'custom-checked' : 'custom-unchecked'));
checkSiblings(parent, checked);
}
else {
$el.parents("li").children('input[type="checkbox"]')
.prop({
indeterminate: true,
checked: false
})
.siblings('label')
.removeClass('custom-checked custom-unchecked custom-indeterminate')
.addClass('custom-indeterminate');
}
}
});
* { margin: 0; padding: 0; }
#page-wrap {
margin: auto 0;
}
.treeview {
margin: 10px 0 0 20px;
}
ul {
list-style: none;
}
.treeview li {
background: url(http://jquery.bassistance.de/treeview/images/treeview-default-line.gif) 0 0 no-repeat;
padding: 2px 0 2px 16px;
}
.treeview > li:first-child > label {
/* style for the root element - IE8 supports :first-child
but not :last-child ..... */
}
.treeview li.last {
background-position: 0 -1766px;
}
.treeview li > input {
height: 16px;
width: 16px;
/* hide the inputs but keep them in the layout with events (use opacity) */
opacity: 0;
filter: alpha(opacity=0); /* internet explorer */
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)"; /*IE8*/
}
.treeview li > label {
background: url(https://www.thecssninja.com/demo/css_custom-forms/gr_custom-inputs.png) 0 -1px no-repeat;
/* move left to cover the original checkbox area */
margin-left: -20px;
/* pad the text to make room for image */
padding-left: 20px;
}
/* Unchecked styles */
.treeview .custom-unchecked {
background-position: 0 -1px;
}
.treeview .custom-unchecked:hover {
background-position: 0 -21px;
}
/* Checked styles */
.treeview .custom-checked {
background-position: 0 -81px;
}
.treeview .custom-checked:hover {
background-position: 0 -101px;
}
/* Indeterminate styles */
.treeview .custom-indeterminate {
background-position: 0 -141px;
}
.treeview .custom-indeterminate:hover {
background-position: 0 -121px;
}
<body class="skin-blue sidebar-mini" style="height: auto; min-height: 100%;">
<!-- changing values in row -->
<input id="rowNumber" class="form-control " type="hidden">
<div class="wrapper" style="height: auto; min-height: 100%; background-color: #ECEFF4;">
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<!-- /.box -->
<div class="box">
<!-- /.box-header -->
<div class="box-body">
<button onclick="addCheckBox()">add</button>
<input id="check" name="checkBoxes">
<div id="page-wrap">
<ul class="treeview">
<li>
<input type="checkbox" name="short" id="short">
<label for="short" class="custom-unchecked">Short Things</label>
<ul id="cc">
</ul>
</li>
</ul>
</div>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<script src="//code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script>
<script type="text/javascript">
function addCheckBox() {
var listElement = document.getElementById('cc');
var check_value = new Array();
check_value[1] = "Yellow";
check_value[2] = "Red";
check_value[3] = "Green";
var li, checkbox, label, br, a;
var title = document.getElementById('check').value;
for (var i = 1; i <= title; i++) {
li = document.createElement("li");
if (i == title)
{
li.className = "last";
}
checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = "short-" + i;
checkbox.id = "short-" + i;
label = document.createElement("label");
label.htmlFor = "short-" + i;
label.className = "custom-unchecked";
label.setAttribute("class", "custom-unchecked");
label.innerHTML = check_value[i];
li.innerHTML += checkbox.outerHTML + label.outerHTML;
listElement.appendChild(li);
/*li.appendChild(checkbox);
//li.appendChild(label);
listElement.appendChild(li);
listElement.appendChild(checkbox);
listElement.appendChild(label); */
}
}
</script>
</body>
- 답변 # 1
- 답변 # 2
코드 관점에서 보면 모든 것이 올바르게 작동합니다.
<올>페이지가로드 된 후 생성 된 DOM 요소에 연결된 이벤트
추가 버튼을 클릭하여 새 DOM 요소를 추가하여 프로그램 적으로 표시합니다
따라서 메모리 누수를 줄이려면 오래된 이벤트를 분리하고 새 이벤트를 만들어야합니다.
당신의* { margin: 0; padding: 0; } #page-wrap { margin: auto 0; } .treeview { margin: 10px 0 0 20px; } ul { list-style: none; } .treeview li { background: url(http://jquery.bassistance.de/treeview/images/treeview-default-line.gif) 0 0 no-repeat; padding: 2px 0 2px 16px; } .treeview > li:first-child > label { /* style for the root element - IE8 supports :first-child but not :last-child ..... */ } .treeview li.last { background-position: 0 -1766px; } .treeview li > input { height: 16px; width: 16px; /* hide the inputs but keep them in the layout with events (use opacity) */ opacity: 0; filter: alpha(opacity=0); /* internet explorer */ -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)"; /*IE8*/ } .treeview li > label { background: url(https://www.thecssninja.com/demo/css_custom-forms/gr_custom-inputs.png) 0 -1px no-repeat; /* move left to cover the original checkbox area */ margin-left: -20px; /* pad the text to make room for image */ padding-left: 20px; } /* Unchecked styles */ .treeview .custom-unchecked { background-position: 0 -1px; } .treeview .custom-unchecked:hover { background-position: 0 -21px; } /* Checked styles */ .treeview .custom-checked { background-position: 0 -81px; } .treeview .custom-checked:hover { background-position: 0 -101px; } /* Indeterminate styles */ .treeview .custom-indeterminate { background-position: 0 -141px; } .treeview .custom-indeterminate:hover { background-position: 0 -121px; }
에서 몇 마디로 새 요소를 만든 후 기능을 추가해야합니다.<body class="skin-blue sidebar-mini" style="height: auto; min-height: 100%;"> <!-- changing values in row --> <input id="rowNumber" class="form-control " type="hidden"> <div class="wrapper" style="height: auto; min-height: 100%; background-color: #ECEFF4;"> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-xs-12"> <!-- /.box --> <div class="box"> <!-- /.box-header --> <div class="box-body"> <button onclick="addCheckBox()">add</button> <input id="check" name="checkBoxes"> <div id="page-wrap"> <ul class="treeview"> <li> <input type="checkbox" name="short" id="short"> <label for="short" class="custom-unchecked">Short Things</label> <ul id="cc"> </ul> </li> </ul> </div> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section> <!-- /.content --> </div> <script src="//code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script> <script type="text/javascript"> function addCheckBox() { var listElement = document.getElementById('cc'); var check_value = new Array(); check_value[1] = "Yellow"; check_value[2] = "Red"; check_value[3] = "Green"; var li, checkbox, label, br, a; var title = document.getElementById('check').value; for (var i = 1; i <= title; i++) { li = document.createElement("li"); if (i == title) { li.className = "last"; } checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.name = "short-" + i; checkbox.id = "short-" + i; label = document.createElement("label"); label.htmlFor = "short-" + i; label.className = "custom-unchecked"; label.setAttribute("class", "custom-unchecked"); label.innerHTML = check_value[i]; li.innerHTML += checkbox.outerHTML + label.outerHTML; listElement.appendChild(li); /*li.appendChild(checkbox); //li.appendChild(label); listElement.appendChild(li); listElement.appendChild(checkbox); listElement.appendChild(label); */ } } </script> </body>
- 답변 # 3
나를 위해 문서 후 컨테이너를 타겟팅해야했습니다
addCheckBox()
$('input[type="checkbox"]').off('change'); // detach event $('input[type="checkbox"]').on('change', checkboxChanged); // add new event
관련 자료
- jquery : Bootstrap ColorPicker는 동적으로 생성 된 요소에서 작동하지 않습니다
- ajax - JavaScript를 사용하여 여러 선택 상자를 동적으로로드
- html - 이름 대신 동적으로 생성 된 입력 필드에 자리 표시자를 표시하는 방법
- java - xml 파일이 아닌 클래스 내에서 동적으로 생성 된 imageView를 정렬하는 방법
- html - 자바 스크립트로 동적으로 생성 된 요소에 인라인 CSS를 추가하는 방법은 무엇입니까?
- 날짜 선택 도구를 실행할 때 다중 선택이 작동하지 않고 Excel에서 VBA로 자동 맞춤
- indexing - GIN 인덱스는`SELECT 1`에서 작동하지 않지만 PostgreSQL에서`SELECT COUNT (*)`를 수행하면 작동합니다
- javascript - 매개 변수가 동적으로 생성 된 이벤트 리스너
- c# - Blazor로 Enum select를 동적으로 빌드하려면 어떻게해야합니까?
- javascript - jquery가 동적으로 추가 된 요소와 작동하지 않습니다
- tidyeval - `dplyr` 동사와 함께 인용되지 않은 문자열 사용 - `select` 및`arrange`가 다르게 작동 함
- javascript - ajax를 사용하여 동적으로 생성 된 앵커 태그 ID 선택
- android - 동적으로 생성 된 목록 Flutter에서 위젯을 동적으로 제거
- vb.net - Visual Basic Forms에서 클릭시 동적으로 생성 된 단추 숨기기
- reactjs - map을 사용하여 콘텐츠를 하드 코딩하는 대신 동적으로 채울 때 머티리얼 UI 탭이 작동하지 않는 이유는 무엇입니까?
- javascript - JS로 만들 때 선택 항목이 옵션과 함께 나타나지 않는 이유는 무엇입니까?
- SQL SERVER Select Distinct ID가 작동하지 않습니다
- r shiny - 이전 입력에서 동적으로 생성 된 selectinput 함수의 입력 인쇄
- javascript - 동적으로 생성 된 요소의 배경색을 2 번 이상 변경할 수 없습니다
- php - Google Sheets 데이터에서 Gravity Forms 선택 (드롭 다운) 메뉴 항목을 동적으로 채우는 방법
관련 질문
- javascript : 사이드 바 토글 버튼에 아무런 조치도 표시되지 않습니다
- javascript : BootStrap 드롭 다운이 닫히지 않고 외부를 클릭합니다
- javascript : ReachJS App.에서 Codepen 프런트 엔드 디자인을 사용합니다
- javascript : jquery는 테이블 행을 밀어 올리십시오
- javascript : ScrollMagic은 웹 사이트가 서버에 업로드되면 작동 중지합니까?
- html : 부트 스트랩 3 : 행을 통해 열을 누릅니다
- javascript : 사이트를 답변시킬 때 나는 내 텍스트가 사라질 것을 원합니다! 도움을줍니다
- javascript : 파일 업로드 JS에서 비디오 또는 이미지를 차별화합니다
- Visual Studio code : Visual Studio code에서 JavaScript, HTML 및 CSS를 사용하여 모바일 응용 프로그램을 어떻게 code합니까?
- JavaScript가있는 입력 값 길이 /상태를 기반으로 요소에 클래스 추가
@ Alx-lark가 말했듯이, 당신이 겪고있는 문제는 초기 페이지로드시 변경 이벤트에 바인딩하는 것이지만 이벤트 바인딩 작동 방식, 추가 된후속확인란 요소입니다 나중에 페이지에 바인딩되지 않습니다. 그의 답변에서 언급 한 해결책-모든 확인란의 바인딩을 해제 한 다음 가장 최근에 추가 한 것을 포함하여 모든 확인란의 바인딩을 다시 설정하십시오.
추가 할 때 개별 확인란을 바인딩하거나
document
와 같이 항상 존재하는 요소를 더 높게 바인딩 할 수도 있습니다.이것은 아마도 가장 쉬운 변경 일 것입니다.
$('input[type="checkbox"]').change(checkboxChanged)
에 와이즈 비즈이벤트 위임이라고하며 https://learn.jquery.com/events/event-delegation/
에서 확인할 수 있습니다. 와이즈 비즈