javascript jquery onclick 按类名 - 如何

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5529475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:31:18  来源:igfitidea点击:

jquery onclick by class name - how to

javascriptjquery

提问by daniel.tosaba

i have: <a class='category' href='view.php?category=1'>category</a>

我有: <a class='category' href='view.php?category=1'>category</a>

i do: $("a.category").click(function(){alert("dsafdfad")})

我做: $("a.category").click(function(){alert("dsafdfad")})

and nothing happens??

什么也没发生??

start("view.php?"); posts("view.php?");

开始(“view.php?”);帖子(“view.php?”);

function start(link){
    $("#country ul").load(link+"mode=start",function(){
    $("#country a").click(function(){
        var link=encodeURI($(this).attr("href"));
        category(link+"&");
        posts(link+"&");
        return false;
        });
    });
}

function start2(link){
    $("#country ul").load(link+"mode=start",function(){
    $("#country a").click(function(){
        var link=encodeURI($(this).attr("href"));
        posts(link+"&");
        return false;
        });
    });
}

function posts(link){
    $("#posts").load(link+"mode=posts",function(){
    $("a.country").click(function(){
        var link=encodeURI($(this).attr("href"));
        category(link+"&");
        posts(link+"&");
        return false;
        });
    $("a.category").click(function(){
        $("#category").css("display","none");
        var link=encodeURI($(this).attr("href"));
        start2(link+"&");
        posts(link+"&");
        return false;
    });
    });
}

function category(link){
    $("#category ul").load(link+"mode=verNav",function(){
        $("#category").css("display","block");
        $("#category a").click(function(){
        var link=encodeURI($(this).attr("href"));
        posts(link+"&");
        return false;
        });
    });
}

回答by BalusC

You need to ensure that the jQuery line is called when the element is already been created and present in the HTML DOM. In other words, do it during $(document).ready()in page head

您需要确保在元素已经创建并出现在 HTML DOM 中时调用 jQuery 行。换句话说,$(document).ready()在页头期间做

<head>
    ...
    <script>
        $(document).ready(function() {
            // Here.
        });
    </script>
</head>  

or put the script at bottom of the page body, afterthe elements of interest.

或者将脚本放在页面正文的底部,感兴趣的元素之后。

<body>
    ...
    <script>
        // Here.
    </script>
</body>

回答by David

Works for me. A few things to check:

对我来说有效。需要检查的几件事:

  • 你是点击链接吗?
  • 您是否在绑定到单击事件之前等待 DOM 加载
  • 是否加载了 jQuery?

回答by ysrb

Make sure that you don't have "alert" as local variable or overriding the jQuery "$".

确保您没有将“警报”作为局部变量或覆盖 jQuery“$”。