onclick复选框事件

时间:2012-02-24 23:36:01

标签: javascript jquery query-string

我要做的就是点击复选框,将其值附加到URL并重定向。我该怎么做?

$(document).ready(function() {   
    var url = 'http://mysite.com/results.aspx';   
        $('.LocType').click (function ()
            {
                var thisCheck = $(this);
            if (thischeck.is (':checked'))
             {
            // Do stuff
             window.location.href = "http://www.yahoo.com";  

             }
        });
}); 

<div class="MyOptions"> 
    Hospitals<input class="LocType" type="checkbox" value="Hospital"/> &#160;  
    Offices<input class="LocType" type="checkbox" value="Office"/> &#160;  
    Facilities<input class="LocType" type="checkbox" value="Facility"/> 
</div> 

2 个答案:

答案 0 :(得分:1)

这真的不是一个好的UI设计 - 用户不希望通过复选框进行导航 - 但这是您想要的代码:

$('.LocType').click (function () {
   if (this.checked) {
       // Do stuff
       window.location.href = "http://www.yahoo.com?paramNameHere=" + this.value;
   }
});

您在函数内部不需要$(this)因为this足以检查checked状态并获得value

您没有说明生成的网址应该是什么样的,所以我只是使用通用paramNameHere参数附加了该值。

答案 1 :(得分:0)

如果你设置你的函数来接收参数javascript会给你一个具有触发事件的元素的事件,你会在下一个代码中归档这个:

$('.LocType').click (function (e) {
   if (this.checked) {
       // Do stuff
       window.location.href = "http://www.yahoo.com" + e.target.value;
      //e.target is the element that fire up the event
   }
});