我是jstree和jQuery的新手,在我的测试树中检查节点时遇到了一点问题。
用户应首先检查他需要的节点,然后单击“摘要”按钮以在警报窗口中获取已检查节点的 ID 列表。我还想导出一个 ID 列表以供在cgi 文件中进一步使用。
这是我的代码:
<!doctype html>
<html>
<head>
<title>jstree test</title>
</head>
<body>
<div id="testtree">
<ul>
<li id="1" title="ID:1"><a>Fruits and Vegetables</a>
<ul>
<li id="11" title="ID:11"><a>Fruit</a>
<ul>
<li id="111" title="ID:111"><a>Apple</a></li>
<li id="112" title="ID:112"><a>Banana</a></li>
</ul>
</li>
<li id="12" title="ID:12"><a>Vegetables</a>
<ul>
<li id="121" title="ID:121"><a>Zucchini</a></li>
<li id="122" title="ID:122"><a>Tomato</a>
<ul>
<li id="1221" title="ID:1221"><a>Red Tomato</a></li>
<li id="1222" title="ID:1222"><a>Green Tomato</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<button>Summary</button>
<script type="text/javascript" src="_lib/jquery.js"></script>
<script type="text/javascript" src="jquery.jstree.js"></script>
<script>
$(document).ready(function() {
var checked_ids = []; // list for the checked IDs
$("#testtree").jstree({
"plugins" : [ "themes", "html_data", "checkbox", "ui" ]
});
})
var button = document.querySelector( "button" );
// If the user clicks on the button, show him the IDs of the checked fruits/vegetables:
button.addEventListener( "click", function( ev ) {
alert( "Your Selection: ");
}, false);
</script>
</body>
</html>
有什么建议我该怎么做?
更新1:
我尝试使用另一篇文章中的 Brad 解决方案,但我仍然无法使其正常工作,因为我不知道如何将 ID 添加到数组中。
这是我的新代码:
<script>
var checked_ids = [];
$(document).ready(function() {
$("#testtree").jstree({
"plugins" : [ "themes", "html_data", "checkbox", "ui" ]
});
// How do I add the IDs to the array?
$("#testtree").jstree('get_selected').attr('id')
})
var button = document.querySelector( "button" );
// If the user clicks on the button, show him the IDs of the checked fruits/vegetables:
button.addEventListener( "click", function( ev ) {
alert("Your Selection: "+ checked_ids.join("\n"));
}, false);
</script>
任何帮助,将不胜感激。
更新 2:
数组仍然没有被填充:
<button>Summary</button>
<script type="text/javascript" src="_lib/jquery.js"></script>
<script type="text/javascript" src="jquery.jstree.js"></script>
<script>
$(document).ready(function() {
$("#testtree").jstree({
"plugins" : [ "themes", "html_data", "checkbox", "ui" ]
});
var arr = new Array();
$("#testtree").jstree('get_checked').each(function(index) {
arr.push($(this).attr('id'));
});
var button = document.querySelector( "button" );
button.addEventListener( "click", function( ev ) {
alert("Your Selection: "+ arr.length + " " + arr[0] + " " + arr[1]);
}, false);
})
</script>