0

这个简单的代码不起作用,只是试图在单击后添加一个类。

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

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>
4

7 回答 7

5

你从来没有关闭你的<a>,但它对我有用。

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:

.on { background-color:red; }

jQuery:

$('a').click(function(){    
      //alert('on'); WORKING
      $(this).addClass('on');
});
于 2013-08-01T17:36:20.370 回答
0

不要忘记关闭您的“a”标签。还要加一个“;” 在你的 jQuery 函数的末尾。

于 2013-08-01T17:38:55.713 回答
0

确保你引用了 jquery 库并将你的代码包装在 dom 中。这对我有用。

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

    $(function () {
        $('a').click(function () {
            //alert('on'); WORKING
            $(this).addClass('on');
        })
    });
</script>
于 2013-08-01T17:40:46.393 回答
0

防止默认行为

$('a').click(function(event){
  event.preventDefault();    
  $(this).addClass('on');
});
于 2013-08-01T17:37:27.910 回答
0

对我有用,只要您将链接的目标更改为"#". (或return false来自点击处理程序。)

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

您永远不会关闭您<a>的 's,但 Firefox 足够聪明,可以为您关闭它们。但不能说其他浏览器。

于 2013-08-01T17:37:38.800 回答
0

您的代码工作正常,请检查以便在加载并准备好 dom 时加载代码。 工作示例

$(document).ready(function(){ 
    $('a').click(function(){    
         $(this).addClass('on');
    });
});
于 2013-08-01T17:37:51.113 回答
0

您的 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>                        

演示

于 2013-08-01T17:38:01.827 回答