我有一个页面,其中有多个hrefs。我想找出哪个href被点击,并基于该href点击我想显示和隐藏一个div?jquery a href recognition
回答
我会假设你有过在href的位置控制,你想拥有最简单的标记可能,在这种情况下,你可以做这样的事情:
<a href="#div1">Toggle Div 1</a>
<a href="#div2">Toggle Div 2</a>
<div id="div1" class="toggleDiv">Div 1 Content</div>
<div id="div2" class="toggleDiv">Div 2 Content</div>
然后打开/切换基于一个div在href
,或者更具体地说是hash
属性,你可以这样做:
$("a").click(function() {
$(".toggleDiv").not(this.hash).hide();
$(this.hash).toggle('fast');
});
这将触发与匹配ID == href
减去哈希相应<div>
并隐藏其他<div>
元素,如果这就是你以后..你只用gi来做这件事把他们分成一个普通的班级,并隐藏除当前链接以外的所有人员。
You can view a demo here看看你是在做什么。
+1对于您描述的问题,这是一个很好的解决方案。当javascript关闭时,它倾向于优雅地退化。很多标签/手风琴插件都是以这种方式工作的。我希望我曾想过把它加到我的例子中。出于某种原因,我*总是*认为hrefs是完整的网址。 – tvanfosson 2010-05-29 12:36:41
你可以附上click处理到锚:
$(function() {
$('a').click(function() {
var href = this.href;
// test the href and show/hide the div:
$('#someDiv').show();
// return false to avoid following the link
return false;
});
});
这应该给你的东西入手:
$('a').click(function()
{
var href = this.href;
// Show/hide your div.
return false;
});
只实现在click
处理函数你的逻辑。
你可以这样做:
$(function(){
$('a').click(function(){
alert('I was clicked, here my href = ' + $(this).attr('href'));
$('#div_id').slideToggle('slow'); // show hide div
return false;
});
});
你说,你要选择基础的href的股利,并可以做,但它比较硬相比,一些其他机制。通常情况下,我发现DOM结构中有一些关系可以替代,或者我可以向链接/ div添加类以使解决方案更简单。例如,通常情况下,该链接与显示的div相邻或位于相同的容器中。在这种情况下,您可以遍历DOM并选择同一个容器的同级或子级的div。
一些例子:在同一容器
链接
$('a.menu-item').click(function() {
$('div.content').hide(); // hide all items
$(this).parent().find('div.content').show(); // show associated item
});
Link在相同的顺序的div
$('a.menu-item').click(function() {
var index = $('a.menu-item').eq(this).index(); // get index
$('div.content').hide().eq(index).show(); // hide all, show corresponding
});
在相同的类(假定链路作为一个单一的,独特的,与div共享课程)
$('a').click(function() {
$('div.content').hide();
$('div').hasClass($(this).attr('class')).show();
});
- 1. jQuery的对A HREF
- 2. a href to upper
- 3. Preg_match_all <a href
- 4. 帆布jQuery的附加链接A HREF
- 5. jQuery Mobile + PhoneGap a href和javascript源码
- 6. 与<a href> tags in Javascript/JQuery
- 7. 修改url_for,A HREF为symfony1.2与jQuery
- 8. jQuery - target.href与<a href="#"><img></a>
- 9. <a href=...> syntax
- 10. a href not picking styling
- 11. asp.net mvc a href id
- 12. PHP A HREF工会
- 13. <a href="#!"> do?
- 14. php a href post isset
- 15. 从按钮获得A HREF
- 16. href表达式<a href="javascript:;"></a>做什么?
- 17. A HREF现在的工作
- 18. <a href=""></a>不工作
- 19. base href url breaks <a href> anchor for fancybox
- 20. 用<a href> tags
- 21. A HREF =#改为的JavaScript:
- 22. 在<a href="form.submit();">
- 23. @ Html.ActionLink到<a href="@Url.Action()>
- 24. CSS和<a href> issue
- 25. 与HTML <a href...>
- 26. <A href> adding " to URL
- 27. 无效A HREF URL的
- 28. href锚文本</a>
- 29. <a href> inside mobile:SelectionList
- 30. 构造A HREF =使用XSLT
这不是一个免费的编码服务。告诉我们你已经尝试了什么,我们可以帮助你填补空白。这只是一个公然告诉我codz。付出一些努力。 – redsquare 2010-05-29 11:37:42
@Delan - 避免标记这样的问题,它已经在meta上详细讨论过了。 – 2010-05-29 11:43:00
redsquare - 您在写作时注意到我的努力 – maztt 2010-05-29 12:00:07