简体   繁体   English

为什么这不起作用? 它甚至没有调用onClick

[英]Why isn't this working? It doesn't even call the onClick

<script type="text/javascript">
$("a.filef").click(function(e){
    alert('hi, it works');
    return false;
});

</script>


<a class="filef" href="" rel="1">A</a>
<a class="filef" href="" rel="2">V</a>

You need to make sure the elements exist first. 您需要确保元素首先存在。 Try this instead: 尝试以下方法:

$(function(){
  $("a.filef").click(function(e){
    e.preventDefault();
    alert("Hi, it works.");
  });
});

Placing your code within: 将您的代码放入:

$(function(){
  /* here */
});

Causes it to wait until the DOM is finished loading before it runs. 使它等待DOM完成加载后再运行。 In your case, it waits until the links exist before it attempts to bind logic to them. 在您的情况下,它将等待直到链接存在,然后再尝试将逻辑绑定到它们。

In some scenarios you will need to run the code before the object exists. 在某些情况下,您将需要在对象存在之前运行代码。 This is the case with many ajax-enabled websites. 许多启用了ajax的网站就是这种情况。 In those cases, jQuery has the $.live() method, which is of a similar look: 在这些情况下,jQuery具有$.live()方法,其外观类似:

$(function(){
  $("a.filef").live("click", function(e){
    e.preventDefault();
    alert("Hi, it works.");
  });
});

Using this, it doesn't matter if the elements already exist, or will show up sometime in the future. 使用此方法,元素是否已经存在或将来是否会出现都无关紧要。 Unless you're working with ajax or late-created elements, I would suggest sticking with the first solution. 除非您使用的是Ajax或后期创建的元素,否则建议坚持使用第一个解决方案。

Your same code is working for me, check out: 您的相同代码对我有用,请查看:

http://jsbin.com/axivo3 http://jsbin.com/axivo3

Put your js code at the bottom of the page or use jquery's ready event which is fired after DOM is available. 将您的js代码放在页面底部,或使用jQuery在DOM可用后触发的ready事件。

Wrap your script in a function and pass it as an argument to $(document).ready(function) or you could write the same as an anonymous function inline. 将脚本包装在一个函数中,并将其作为参数传递给$(document).ready(function),也可以与匿名函数内联代码一样编写。

<script type="text/javascript">
$(document).ready(function(){
 $("a.filef").click(function(e){
    alert('hi, it works');
    return false;
 });
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM