我正在尝试深入研究jQuery,但希望得到一些关于如何以最佳方式做事的反馈,
我有一个包含项目的列表,每个项目都包含一个隐藏的div,应该在点击它的父项时显示,
list
div:ed item1 with link
hidden div
div:ed item2 with link
hidden div
..
我目前的解决方案是通过它的id跟踪调用链接,然后重复使用该ID来显示正确的隐藏链接:
$(document).ready(function() {
//jQ should only trigger on links with id="cmLinkINT"
$("a").click(function() {
//see if it's a comment request.
var s = $(this).attr("id");
if (s.indexOf('cmLink') != -1) {
//ok, it was a 'show'-link, get the id..
var j = s.substring(6);
//ok, now I have the id i want to show (detailsINT)
return false;
}
});
});
我不清楚最好的方法,
我应该使用id来请求或跟踪父div的ID。
如何避免代码在任何链接上触发?类
更新
html示例:
<div class="unit">
<img class="unitImg" src="imgcache/some.jpg" width="98" height="98" alt="some"/>
<div class="unitInfo">
<h1>my unit</h1>
<h2>/further..</h2>
<p><a href="#" class="showDetails">show details...</a></p>
<div style="visibility: hidden;" id="unitDetails2">
<p>peekaboo...</p>
</div>
</div>
</div>
<div class="unitGap"></div>
<div class="unit" ...>
感谢任何反馈,
问候
//吨
答案 0 :(得分:3)
我建议你在锚点上放一个用来显示隐藏div的类。
所以,你的jquery将是(其中'揭示'是类):
$("a.reveal").click(function() {
$(this).next("div").show();
return false;
});
或者,您可以使用切换来显示/隐藏多次点击
$("a.reveal").toggle(function() {
$(this).next("div").show();
return false;
});
注意:我认为隐藏的div是显示它的锚点的兄弟。也许发布您的实际标记。
答案 1 :(得分:1)
$("a[id^=cmLink]").click(function() {
$(this).parent().find("div[id=^details]").toggle();
});
假设您要切换的div位于也包含链接的div中。
答案 2 :(得分:0)
Use .delegate()
在列表中放置一个处理程序,用于查找<a>
元素的点击次数,然后使用.next()
到show()
遍历到<div>
:
$('#myList').delegate('a','click',function() {
$(this).next().show();
return false;
});
这假定列表的标识为myList
。它将处理<a>
元素内的点击。
由于您没有发布实际的HTML标记,因此很难判断这是否是完全正确的代码。如果您在问题中发布HTML,我可以给出更明确的答案。
答案 3 :(得分:0)
您可以在此处使用attribute starts with选择器([attr="value"]
)。然后,您可以在父div的上下文中找到子div。
$('a[id^="cmLink"]').click(function() {
$(this).parent().find('div').show();
});
答案 4 :(得分:0)
您可以使用更具体的选择器,例如通过向cm链接提供特定类(例如cmLink
),然后使用类$("a.cmLink")
之类的类选择器。
或者,您只能选择#cm
列表后代的链接,例如$("#cm > div.item > a")
。