HTML:
<option data-task-hours="100" value="1"> - Parent Task</option>
<option data-task-hours="50" value="2"> - - Child task 1 </option>
<option data-task-hours="50" value="5"> - - Child task 2</option>
jQuery获取Parent Task
var selectedOption = $('#dropDownId option:selected')
var selectedOptionValue = selectedOption.data('task-hours');
var sum = 0;
selectedOption.nextAll().each(function(){
if (sum < selectedOptionValue) {
sum += $(this).data('task-hours');
} else {
sum = selectedOptionValue;
return false;
}
});
这给出了Parent Task
下的子任务的总值。如果那时我需要在Child Task 1
所需的HTML下添加子子将
<option data-task-hours="100" value="1"> - Parent Task</option>
<option data-task-hours="50" value="2"> - - Child task 1 </option>
<option data-task-hours="25" value="3"> - - - Sub Child task 1.1</option>
<option data-task-hours="50" value="5"> - - Child task 2</option>
nextAll()
将获取doprdown中任何选定选项下的所有后续选项。我如何知道Child Task 1
下是否Sub Child task 1.1
考虑了亲子关系?
答案 0 :(得分:1)
您需要为父子层次结构添加属性,例如
对任何父选项的子项使用data-parent属性,例如data-parent="value of parent option"
(data-parent =&#34; 2&#34;)
所以html看起来像,
<option data-task-hours="100" value="1"> - Parent Task</option>
<option data-task-hours="50" value="2"> - - Child task 1 </option>
<option data-task-hours="25" value="3" data-parent="2"> - - - Sub Child task 1.1</option>
<option data-task-hours="50" value="5"> - - Child task 2</option>
现在,您需要传递nextAll()中的data-parent
属性,
selectedOption.nextAll("[data-parent='"+selectedOption.val()+"']").each(function(){
if (sum < selectedOptionValue) {
sum += $(this).data('task-hours');
} else {
sum = selectedOptionValue;
return false;
}
});
答案 1 :(得分:0)
JSFiddle您可以获得总工时:
var selectedOption = $('#dropDownId option:selected')
var selectedOptionValue = selectedOption.data('task-hours');
var sum = 0;
var currentLevel = selectedOption.text().split('-').length;
selectedOption.nextAll("option").each(function() {
if(this.text.split('-').length > currentLevel){
if (sum < selectedOptionValue) {
sum += $(this).data('task-hours');
} else {
sum = selectedOptionValue;
return false;
}
}
});
console.log(sum);