如何在HTML中覆盖覆盖href的jQuery中停止返回false

时间:2013-01-30 21:14:12

标签: jquery html5

HTML
我正在添加我的两个链接,它将我的“未答复”链接发送到我的管理员控制器,并将我的“已回答”链接发送到我的管理控制器中的一个功能。

<h2 class="unanswered">
   <?=anchor('admin/', 'Unanswered', array('class' => 'selected'))?>
</h2>

<h2 class="answered">
   <?=anchor('admin/answered_posts', 'Answered')?>
</h2>

Jquery的
在这里,我只是尝试添加和删除我的链接样式。当我保持返回false时,我的样式工作正常,但我在html锚点中的href不再运行,所以我无法从我的控制器中取回所需的帖子。当我删除返回false时,我的href工作正常,我从控制器中恢复了我需要的东西,但是我在jQuery中添加的样式不再有效。

$('.unanswered').click(function(){
       $('.answered a').removeClass('active');
       $('.unanswered a').addClass('active'); 
       return false;
     });

     $('.answered').click(function(){
       $('.unanswered a').removeClass('active');
       $('.answered a').addClass('active');
       return false;
     });

旁注
我也尝试过:

$('.unanswered').click(function(e){
       e.preventDefault();
       $('.answered a').removeClass('active');
       $('.unanswered a').addClass('active'); 
     });

     $('.answered').click(function(e){
       e.preventDefault();
       $('.unanswered a').removeClass('active');
       $('.answered a').addClass('active');
     });

1 个答案:

答案 0 :(得分:2)

我会参考有关问题的评论 - 如果我理解你的意图(点击链接,更新服务器后面的内容,并在页面上应用样式而不重新加载页面)这可能是你的意思我想用AJAX做。例如(未经测试的代码):

$('.unanswered, .answered').click(function() {
    $.ajax({
        url: $(this).attr('href')
    }).done(function() {
        /* You'll need to add some logic in here to remove the active class from
        the answered or unanswered question if it exists. Depending on the rest of your 
        HTML, this could be done with something like $(this).closest('myWrapper').find('a.active').removeClass('active') */

        /* Once you've cleaned up any active classes, add an active class to this element */
        $(this).addClass('active');

    });
});

更多关于jQuery AJAX的阅读:http://api.jquery.com/jQuery.ajax/

由于我不确切地知道你正在尝试做什么,你也可以尝试这个(它将更新类,然后提交请求)。您可能看不到反映的CSS更改,因为页面将快速重新加载。

$('.answered').click(function() {
   // Set up the classes here
   $('.unanswered a').removeClass('active');
   $(this).addClass('active');

   /* When this element has an active class, then it will redirect to the link's URL, the HREF attribute. We do this check because javascript is asynchronous, all lines can run at the same time, so this prevents window.location from being called before the class is changed */
   if($(this).hasClass('active')) {
       window.location = $(this).attr('href');
   }

   // Still return false to prevent the default redirect that would happen without javascript.
   return false;
 });