无法获得jQuery单击以正确注册元素

Mik*_*ran 0 jquery

这里看到j​​sfiddle

我试图让"阅读更多"链接向下滑动并在点击时显示隐藏的内容,但我似乎无法正确注册点击功能.我做了明显错误的事吗?

基本的HTML布局

<div id="wrapper">
    <div id="aHidden">some long text here</div> <!--defaulted hidden with css-->
    <div id="aBtn" class="bio-readMore">read more...</div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是我试图用来做这个的jQuery:

$(document).ready(function() {
    $("div").each(function(idx) {
        if ($(this).hasClass('bio-readMore')) {
            var thename = this.id.replace("Btn", "Hidden");
            var sel = "#" + thename;
            $(sel).click(function() {
                alert("running click for element with value " + this.id);
                if ($(this).is(":hidden")) {
                    $(this).slideDown("slow");
                } else {
                    $(this).slideUp();
                }
            });
        }
    });
});?
Run Code Online (Sandbox Code Playgroud)

Mar*_*man 7

使用现有标记,您可以使用以下内容轻松替换您的点击注册:

$(".bio-readMore").on("click", function(){
    $(this).prev().slideToggle();
});
Run Code Online (Sandbox Code Playgroud)

jsfiddle的例子

如果你想修复你的代码,你可以让你的一些选择器颠倒过来:

$(document).ready(function() {
    $("div").each(function(idx) {
        if ($(this).hasClass('bio-readMore')) {
            var thename = this.id.replace("Btn", "Hidden");
            var sel = "#" + thename;
            $(this).click(function() {  //<--- On the <a/> not the hidden element
                alert("running click for element with value " + this.id);
                if ($(sel).is(":hidden")) { // <----you want to check the hidden not the <a/>
                    $(sel).slideDown("slow");
                } else {
                    $(sel).slideUp();
                }
            });
        }
    });
});?
Run Code Online (Sandbox Code Playgroud)

jsfiddle的例子