onclick复选框事件

onclick checkbox event

本文关键字:事件 复选框 onclick      更新时间:2023-09-26

我所要做的就是点击复选框,将其值附加到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> 

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

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

函数中不需要$(this),因为this足以检查checked状态并获得value

您没有说明生成的URL应该是什么样子,所以我只是在值后面添加了一个通用的paramNameHere参数。

如果您将函数设置为接收参数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
   }
});