我正在尝试根据列表项的文本内容向列表项添加一个类--这是一种变通方法,可以在动态生成的菜单中突出显示项,但该类将应用于所有列表项。是不是因为我在比较两种不同类型的变量而出错?
$(document).ready(function() {
$('article[id^=post]').filter(function(){
var categorySelected = this.className.match(/\bcategory-\w+\b/).toString();
var trimmed = categorySelected.replace(/^category-/,'');
if ( $(this).hasClass(trimmed) ) {
alert ('article has category = true, location = ' + trimmed );
$('div#categories-3 li').each(function(index) {
var listItem = $(this).text().toLowerCase().replace(' ','-').toString();
if ( listItem = trimmed ) {
alert ('listItem = ' + listItem + ' trimmed = ' + trimmed);
$(this).addClass('current-cat');
};
});
};
});
});对于..thanks的建议,已经做出了改变并投入了更多的诊断,但仍然无法取得突破。在这个版本中,不会添加'current-cat‘类:
$(document).ready(function() {
$('article[id^=post]').filter(function(){
var categorySelected = this.className.match(/\bcategory-\w+\b/).toString();
var trimmed = categorySelected.replace(/^category-/,'');
if ( $(this).hasClass(trimmed) ) {
alert ('article has category = true\nlocation = ' + trimmed + '\ntrimmed var is type of ' + (typeof trimmed) );
$('.cat-item').each(function(index) {
$(this).addClass('item-' + index);
var listItem = $(this).text().toLowerCase().replace(' ','-');
alert ( 'listItem var is type of ' + typeof listItem ) ;
if ( listItem == trimmed ) {
alert ('listItem = ' + listItem + ' trimmed = ' + trimmed);
$(this).addClass('current-cat');
}
});
};
});
});下面是它的HTML:
<div id="container">
<article id="post-49" class="post-49 post type-post status-publish format-standard hentry category-reykjavik reykjavik photograph">
some content
</article>
<div id="categories-3" class="widget widget_categories">
<h4 class="widgettitle">
Location
</h4>
<ul>
<li class="cat-item cat-item-1">
<a href="#">
Havana
</a>
</li>
<li class="cat-item cat-item-3">
<a href="#">
London
</a>
</li>
<li class="cat-item cat-item-13">
<a href="#">
Reykjavík
</a>
</li>
</ul>
</div>
</div>发布于 2011-11-18 02:08:08
在您的代码中,由于存在空格和换行符,这种比较永远不会为真。
if (listItem == trimmed) {通过在if前面添加比alert更好的控制台行来调试它。
console.log(listItem + "\t" + trimmed);
if (listItem == trimmed) {另外,为了提高性能,您不应该一遍又一遍地调用$(this)。它每次都会创建一个新的jQuery对象,这使得代码运行的时间更长。将其缓存到一个变量中,并反复使用该变量。
发布于 2011-11-17 17:02:09
将if ( listItem = trimmed )更改为if ( listItem == trimmed )
发布于 2011-11-17 17:02:36
if ( listItem = trimmed ) {应该是
if ( listItem == trimmed ) {https://stackoverflow.com/questions/8164449
复制相似问题