我有一个简单的清单。
<ul id="testCaseList" class="list-group testCaseList">
<li class="list-group-item justify-content-between" style="">test1 (hi)</li>
<li class="list-group-item justify-content-between" draggable="false" style="">test2 (bye)</li>
<li class="list-group-item justify-content-between" style="">test3 (hello)</li>
</ul>
我想创建一个包含数组的数组。用名字(类型)。所以结果会是这样的:
[
["test1", "hi"]
["test2", "bye"]
["test3", "hello"]
]
我正在尝试这样的事情,但我遇到了多个错误。
var testCaseList = $('#testCaseList');
$.each(testCaseList, function (index, item) {
console.log(item);
data.push(item.text());
});
console.log(data);
未捕获的TypeError:item.text不是函数
在HTMLUListElement。 (创建-flow.js:182)
在Function.each(jquery-3.2.1.min.js:2)
在a.onUpdate(create-flow.js:180)
在k(Sortable.min.js:2)
at a._onDrop(Sortable.min.js:2)
在a.handleEvent(Sortable.min.js:2)
答案 0 :(得分:3)
要实现此目的,您可以使用map()
从匹配的元素构建数组。在map()
处理程序中,您可以使用带有组的正则表达式来提取所需的文本值。试试这个:
var arr = $('ul li').map(function() {
var matches = /(.*) \((.*)\)/g.exec($(this).text());
matches[0] = '';
return [matches];
}).get();
console.log(arr);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="testCaseList" class="list-group testCaseList">
<li class="list-group-item justify-content-between" style="">test1 (hi)</li>
<li class="list-group-item justify-content-between" draggable="false" style="">test2 (bye)</li>
<li class="list-group-item justify-content-between" style="">test3 (hello)</li>
</ul>
&#13;
答案 1 :(得分:1)
var listGroupItem = $('.list-group-item');
var data = [];
$.each(listGroupItem, function (index, item) {
var string = item.innerHTML.split('(').join().split(')');
data.push(string);
data = data.filter(function(n){
return n != "";
});
});
console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="testCaseList" class="list-group testCaseList">
<li class="list-group-item justify-content-between" style="">test1 (hi)</li>
<li class="list-group-item justify-content-between" draggable="false" style="">test2 (bye)</li>
<li class="list-group-item justify-content-between" style="">test3 (hello)</li>
</ul>