选择要显示和隐藏的元素,遍历问题!(jQuery)

Selecting elements to show and hide, traversal issue! (jQuery)

本文关键字:问题 遍历 jQuery 元素 显示 隐藏 选择      更新时间:2023-09-26

我一直在尝试parent()/children()/find()和选择器语法的每一种组合。show()是我隐藏在文档中的网页元素,但我就是无法让它工作!如果有人能看一看,我将不胜感激。。

如果你去投资组合部分,你可以在这里看到它的直播->http://holly.im/。

无论如何,html看起来像这样:

<div id="portfolio">
<h1>Heading</h1>
<div class ="little_column">
  <div class="project"> 
    <a href="#c++_games_engine_construction" class="projlink"> click </a>
  </div>    
</div>
<div id="c++_games_engine_construction" class="big_column">
    <?php include "projects/C++_game_engine_construction.php"; ?>
</div>
</div>

以及相关的jquery:

$(document).ready(function() {  
    //hide all the big_columns / 
    // project details within the portfolio page
    $('#portfolio').find('.big_column').hide(); //This seems to be working
});
$(function(){
    $('.project').click(function () {
        var selectedProject =
            $(this).children('a.projlink').attr('href');
        $(this).parent().parent().find(selectedProject).show(); //My most recent attempt, I though maybe i needed to go up the heirachy then back down? But whatever i try it doesn't show.
        return false;
    });
});

真的是这样,谢谢!

在元素的ID中包含字符+会导致jQuery变得混乱,因为+字符是为下一个相邻选择器保留的。

如果您从代码中删除这些字符,它就可以正常工作。正如对此答案的一条评论中所提到的,由于href本质上是要显示的项目的ID,因此您可以直接选择它。

HTML

<div id="portfolio" class="section">
    <h1>Heading</h1>
    <div class="little_column">
        <div class="project"> <a href="#c_games_engine_construction" class="projlink"> click </a>
        </div>
    </div>
    <div id="c_games_engine_construction" class="big_column">
        I'm hidden at first!
    </div>
</div>

JS-

$(document).ready(function () {
    //hide all the big_columns / 
    // project details within the portfolio page
    $('#portfolio').find('.big_column').hide(); //This seems to be working
});
$(function () {
    $('.project').click(function () {
        var selectedProject = $(this).children('a.projlink').attr('href');
        $(selectedProject).show(); //My most recent attempt, I though maybe i needed to go up the heirachy then back down? But whatever i try it doesn't show.
        return false;
    });
});

jsfiddle

问题在于选择器中的+。需要对其进行转义,因为它在Selectors API中具有特殊含义(对于ID无效)

如果从hrefid中删除了++,则可以正常工作。


或者,您可以执行.replace(/'+/g, "''+")

var selectedProject = $(this).children('a.projlink').attr('href').replace(/'+/g, "''+")

脱离主题:您不需要两个.ready()调用,这就是您所拥有的,但使用不同的语法

正如其他人所提到的,您的问题是jQuery滥用了+字符。因此,简单的解决方案是:不要使用jQuery——或者至少不要用于选择器。由于您拥有的每个目标都是一个id选择器,我们可以很容易地将其更改为

$(document).ready(function() {  
    $('#portfolio').find('.big_column').hide();
    $('.project').click(function () {
        var selectedProject = $(this).find('a').attr('href'); // a littebit simplified
        var el = document.getElementById(selectedProject.slice(1));
        $(el).show();
        return false;
    });
});