简体   繁体   English

使用jQuery $(this).addClass不起作用,简单代码不起作用

[英]using jQuery $(this).addClass not working, simple code not working

this simple code is not working, just trying to add a class once clicked on. 这个简单的代码不起作用,仅在单击后尝试添加一个类。

    $('a').click(function(){    
      //alert('on'); WORKING
      $(this).addClass('on');
    })

The HTML is simply.. HTML很简单。

    <ul>
 <li><a href="">List Item 1</li>
 <li><a href="">List Item 2</li>
 <li><a href="">List Item 3</li>
 <li><a href="">List Item 4</li>                        
   </ul>

You didn't ever close your <a> , but it's working for me otherwise. 您从未关闭过<a> ,但是它对我有用。

http://jsfiddle.net/L3nyE/ http://jsfiddle.net/L3nyE/

<ul>
    <li><a href="#">List Item 1</a></li>
    <li><a href="#">List Item 2</a></li>
    <li><a href="#">List Item 3</a></li>
    <li><a href="#">List Item 4</a></li>                        
</ul>

CSS: CSS:

.on { background-color:red; }

jQuery: jQuery的:

$('a').click(function(){    
      //alert('on'); WORKING
      $(this).addClass('on');
});

Prevent the default behaviour 防止默认行为

$('a').click(function(event){
  event.preventDefault();    
  $(this).addClass('on');
});

Works for me, provided you either change the target of the links to "#" . 为我工作,只要您将链接的目标更改为"#" (Or return false from the click handler.) (或从点击处理程序return false 。)

http://jsfiddle.net/jaNCq/1/ http://jsfiddle.net/jaNCq/1/

You never close your <a> 's but Firefox is smart enough to close them for you. 您从不会关闭<a> ,但是Firefox足够聪明,可以为您关闭它们。 Can't say for other browsers though. 虽然不能说其他浏览器。

Your code working fine, check so you load your code when the dom is loaded and ready. 您的代码工作正常,请检查以便在dom加载并准备就绪时加载您的代码。 Working example 工作实例

$(document).ready(function(){ 
    $('a').click(function(){    
         $(this).addClass('on');
    });
});

Your HTML is Incorrect 您的HTML不正确

<ul>
<li><a href="#">List Item 1</a></li>
 <li><a href="#">List Item 2</a></li>
 <li><a href="#">List Item 3</a></li>
  <li><a href="#">List Item 4</a></li>                        

Demo 演示版

Don't forget to close your "a" tags. 不要忘记关闭您的“ a”标签。 Also add a ";" 还添加一个“;” at the end of your jQuery function. 在jQuery函数的末尾。

Make sure you have the jquery lib referenced and wrap your code in the dom ready. 确保已引用了jQuery lib,并将代码包装在dom中。 This worked for me. 这对我有用。

<style>
    .on{
        color:red;
    }
</style>
<script>

    $(function () {
        $('a').click(function () {
            //alert('on'); WORKING
            $(this).addClass('on');
        })
    });
</script>

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

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