我有一系列称为过滤器的 html 内容,它们是从数据库生成的。内容可以根据页面动态变化。我已经为每个主 div 提供了 css ID,并在循环时附加了一个数字。下面是一个示例片段:
<div><a id="filter-1">Brands</a></div>
<div id="filter-op-1">This is option 1</div>
<div><a id="filter-2">Size</a></div>
<div id="filter-op-2">This is option 2</div>
<div><a id="filter-3">Color</a></div>
<div id="filter-op-3">This is option 3</div>
ID filter-1
和 filter-op-1
等等都是根据循环次数生成的,所以我们不知道页面上会为过滤器生成多少内容。
我需要通过 a
显示/隐藏 filter-op-x 内容点击,所以我写了下面的 jQuery 代码:
$(document).ready(function () {
$('div a').click(function() {
var self = $(this);
var cssId = self.attr('id');
var child = $('div#filter-op-'+cssId);
child.toggle();
});
});
现在的问题是它不能以这种方式工作,但是如果我删除 cssId
在 js 代码和 -1
中, -2
等在 html 中,它开始工作,但它隐藏所有内容,无论是哪个 a
我点击了。
我不明白是什么导致了这个问题。任何人都可以解释这个问题并提供一些好的建议如何处理它?
谢谢
最佳答案
您需要像这样对您的 JS 代码进行一些更改:
$(document).ready(function () {
$('div a').click(function() {
var self = $(this);
var cssId = self.attr('id');
console.log(cssId); // This gives the `a` id.
var id = cssId.split("-")[1]; // Split and get the number part
console.log(id);
var child = $('div#filter-op-'+id); // append the number part here
child.toggle();
});
});
关于javascript - 显示隐藏内容时奇怪的 jQuery 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33185496/