on("click", event) 触发而不点击 [英] on("click", event) firing without clicking

查看:33
本文介绍了on("click", event) 触发而不点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于这个主题有类似的问题,但他们的回答对我的问题不起作用.

我正在尝试使用 jQuery 的 on("click") 来触发一个函数,该函数只是更改被单击的 id 的类.但是该函数在页面加载时被调用,然后如果您单击应该触发该函数的内容,它就不会触发.

Im trying to use jQuery's on("click") to fire a function that simply changes the class of the id which was clicked. But the function is called when the page is loaded and then if you click on what should fire the function it wont.

这是html:

<nav>
    <ul>
        <li id="all" class="tab-current"><a><span>All Departments</span></a></li>
    </ul>
</nav>

这里是js:

var $all = $("#all");
$all.on("click", function(){
    tabClicked("all");
});

我也试过这个:

$all.on("click", tabClicked("all"));

这是函数:

function tabClicked(input){
    //do some stuff here
}

有什么想法吗?提前致谢!:)

Any ideas? Thanks in advanced! :)

推荐答案

var $all = $("#all");

$all.on("click", function(){
    tabClicked("all");
});

尝试像这样编辑它.$(function() {}); 就像 $(document).ready(),所以用 function(){} 代替$(function() {});.

Try editing it like this. $(function() {}); is like $(document).ready(), so put function(){} instead of $(function() {});.

出于某种原因,如果 script 标签在 html 中的元素之后,它就会被触发.我用外部 JS 等尝试了你的代码 - 没有用.

For some reason, it is firing if script tag is after elements in html. I tried your code with external JS and etc. - didn't work.

试试这样:JSFiddle

编辑 2:你应该把你的处理程序放在 $(document).ready() 函数中你想要的任何地方,这就是原因.

EDIT 2: You should put your handler in $(document).ready() function anywhere you want, that's the reason.

$( document ).ready(function() {
 var $all = $("#all");
 $all.on("click", function(){
    alert("click");
 });
});

这篇关于on("click", event) 触发而不点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆