我有一个项目列表,其中包含使用该data-type
属性的标签。我正在尝试遍历项目以获取数组中的每个标签。如果列表项有多个标签(用逗号分隔),我想拆分标签并清理任何空白。
这是我的 HTML:
<div class="article-wrap">
<ul class="articles">
<li sata-type="tag3"> <a href="#">LTE opens vast new business and revenue opportunities. Here's how to get ready.</a>
</li>
<li data-type="tag3"> <a href="#">Bringing NFC into the Digital Home</a>
</li>
<li data-type="tag3, tag4"> <a href="#">Keep Up with Rapidly-changing Wi-Fi Standards, Techniques and Markets</a>
</li>
<li data-type="tag1"> <a href="#">Technicolor Professional Services help NSPs reduce software vulnerability</a>
</li>
<li data-type="tag2, tag3"> <a href="#">Our New Satellite/terrestrial HD Set-top Box Provides a Smooth Path to HDTV.</a>
</li>
</ul>
</div>
这是我的 JS:
$(function () {
var items = $('.article-wrap li'),
itemsByTags = {};
// Looping though all the li items:
items.each(function (i) {
var elem = $(this),
tags = elem.data('type').split(',');
// Adding a data-id attribute
elem.attr('data-id', i);
$.each(tags, function (key, value) {
// Removing extra whitespace:
value = $.trim(value);
if (!(value in itemsByTags)) {
// Create an empty array to hold this item:
itemsByTags[value] = [];
}
// Each item is added to one array per tag:
itemsByTags[value].push(elem);
});
});
});
我相信这应该可以正常工作,可惜我得到Uncaught TypeError: Cannot call method 'split' of undefined。你可以在这里看到这个:http: //jsfiddle.net/94UUF/2/
我可以使用相同的items
var 来修改 CSS 等,但该.split
功能似乎不想玩。请指教!