【问题标题】:Targetting div using an anchor jquery使用锚 jquery 定位 div
【发布时间】:2014-08-21 15:45:38
【问题描述】:

我在从 href 链接定位 div 时遇到问题。

我可以使用 div 来做到这一点。例如,我可以使用这样的代码来定位 div。

<div id="nav"> 
<a href="index1.html">home</a> 
<a href="index.php">why</a> 
<a href="search.php">a story</a> 
<a href="testpage.php">a picture</a> 
</div>    

它以这个 div 为目标,这是点击特定链接后它会出现的位置:

<div id="content">
</div>

..这个jquery是

<script type="text/javascript">
$(function(){
$('#nav'a).click(function(e) { 
$('#content').hide().load( $(this).attr('href') , function(){
$('#content').show()
})
return false
})
})
</script>

但是,我想在不使用 div 的情况下使用此功能,不幸的是,当我尝试在锚点上使用 id“nav”时,我遇到了麻烦,它不起作用,它似乎加载到另一个页面但没有到 div。

下面是我想要的代码结果

<div> 
<a id="nav" href="index1.html">home</a> 
<a id="nav" href="index.php">why</a> 
<a id="nav" href="search.php">a story</a> 
<a id="nav" href="testpage.php">a picture</a> 
</div>    

我怀疑它与这行代码有关,我在谷歌的某个地方发现这个函数中的“a”指的是一个 div,虽然我不太确定

$('#nav a').click(function(e)

提前致谢!

【问题讨论】:

    标签: jquery html search href target


    【解决方案1】:

    首先,ID 应该是唯一的,如果您要申请群组,请改用 Class。所以把它改成这样:

    <div> 
        <a class="navlink" href="index1.html">home</a> 
        <a class="navlink" href="index.php">why</a> 
        <a class="navlink" href="search.php">a story</a> 
        <a class="navlink" href="testpage.php">a picture</a> 
    </div>  
    

    然后只需绑定到类:a.navlink.navlink 就可以了:

    $('.navlink').click(function(e) { 
        e.preventDefault();
        $('#content').hide();
        $('#content').load($(this).attr('href') , function(){
            $('#content').show();
        });
    });
    

    【讨论】:

    • 非常感谢您!你帮了我很多,还让我知道 id 用于一个组,而 class 是特定的。
    • 反之亦然:id="something" (#id) 是唯一的,特定于一个元素。 class="something" (.something) 用于一组元素。很高兴能提供帮助。
    【解决方案2】:

    将 a 移到引号内:

    $(function(){
        $('#nav'a).click(function() { 
            $('#content').hide().load( $(this).attr('href') , function({
            $('#content').show()
        });
        return false;
        )});
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多