我正在使用 OpenCart v2.2.0。在类别页面上,我有属于该类别的每个产品的显示/隐藏链接,该链接应该缩短或隐藏产品信息。问题是它仅针对第一个产品信息进行切换,无论我单击哪个显示/隐藏链接。其他人不切换他们的信息,他们都只切换第一个。到目前为止,我有这段代码:
在 category.tpl 中:
<div class="caption">
<h4><a style="width:140%;" href="<?php echo $product['href']; ?>"><?php echo $product['name']; ?></a></h4>
<a href="javascript:toggleDiv('myContent');" style="padding: 5px 10px;">Show/Hide</a>
<div id="myContent" style="display:none;">
<p class="description"><b>About:</b> <?php echo $product['description']; ?></p>
<?php if ($product['manufacturer']) { ?>
<b><?php echo "<strong>Manufacturer:</strong>" ?></b> <a href="<?php echo $product['manufacturers']?>"><span itemprop="brand"><?php echo $product['manufacturer']; ?></span></a>
<?php } ?></br>
<?php echo "<strong>For models:</strong> " . $product['model']; ?></br>
<?php echo "<strong>Manufacturer code:</strong> " . $product['mpn']; ?></br>
</div>
</div>
还有:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function toggleDiv(divId) {
$("#"+divId).toggle();
}
</script>
有谁知道如何让其他人也切换他们自己的信息?显然,我一直在尝试解决这个问题,但没有运气。这就是我想出的全部,但这并不好。
最佳答案
首先 id
在同一个文档中应该是唯一的,所以用通用类替换重复的,然后使用这些类进行选择,例如给你的 anchor a
一个类就像我的示例中的 toggle
然后将点击事件附加到类:
$('body').on('click','.toggle',function(e){
e.preventDefault();
$(this).closest('.caption').find('.myContent').toggle();
//Or
$(this).next('.myContent').toggle();
})
我在这里建议避免使用内联事件 onclick
并从您的 javascript 代码附加点击事件。
希望这对您有所帮助。
$('body').on('click','.toggle',function(e){
e.preventDefault();
$(this).closest('.caption').find('.myContent').toggle();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="caption">
<h4> <a style="width:140%;" href="">Name1</a></h4>
<a href="" style="padding: 5px 10px;" class='toggle'>Show/Hide</a>
<div class="myContent" style="display:none;">
<p class="description"><b>About:</b> description1</p>
<b><strong>Manufacturer:</strong></b>
<a href="">
<span itemprop="brand">manufacturer</span>
</a>
<br>
<strong>For models:</strong> Manufacturer code:
</div>
</div>
<div class="caption">
<h4><a style="width:140%;" href="">Name2</a></h4>
<a href="" style="padding: 5px 10px;" class='toggle'>Show/Hide</a>
<div class="myContent" style="display:none;">
<p class="description"><b>About:</b> description2</p>
<b><strong>Manufacturer:</strong></b>
<a href="">
<span itemprop="brand">manufacturer</span>
</a>
<br>
<strong>For models:</strong> Manufacturer code:
</div>
</div>
关于javascript - 切换每个产品的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41483750/