我有一个项目列表,其中将包含使用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
函数似乎不想发挥作用。请指教!
最佳答案
你注意到了吗:
<li sata-type="tag3">
是sata
而不是data
,因此出现错误:
Uncaught TypeError: Cannot call method 'split' of undefined.
关于javascript - 通过 jQuery 分离和清理数据属性中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15091691/