简体   繁体   English

ASP.Net用户控件中的JQuery自定义事件

[英]JQuery custom event in ASP.Net User Control

I have an ASP.Net user control that contains some checkboxes, and I want to use JQuery to raise an event from the user control when one of the checkboxes is clicked. 我有一个包含一些复选框的ASP.Net用户控件,并且当单击其中一个复选框时,我想使用JQuery从用户控件中引发事件。 Here is the JQuery code in the user control where I'm trying to raise the event: 这是用户控件中我要引发事件的JQuery代码:

         $(document).ready(function() { 
            $(':checkbox').click(function(){
               $('#hfRemainingInstalls').trigger('CheckBoxClicked');
            });
         });

and here is the JQuery code in the containing aspx page where I'm trying to subscribe to the event: 这是我试图订阅该事件的包含aspx页面中的JQuery代码:

          $(document).ready(function() {
              $("p").bind('CheckBoxClicked', function(e) {    
                 alert("checkbox clicked");       
             });
          });

I'm never seeing my alert when I click on one of the checkboxes. 当我单击复选框之一时,我再也看不到警报。 Anyone know what might be the problem here? 有人知道这可能是什么问题吗?

so is there a relationship between the Id tags P and Id hfRemainingInstalls 那么Id标签P和Id hfRemainingInstalls之间是否有关系

1: Solution 1:解决方案

$(':checkbox').click(function(){
    $("p").trigger('CheckBoxClicked');
});

$(document).ready(function() {
  $("p").bind('CheckBoxClicked', function(e) {    
     alert("checkbox clicked");       
  });
});

2: Solution 2:解决方案

$(':checkbox').click(function(){
    $("#hfRemainingInstalls").trigger('CheckBoxClicked');
});

$(document).ready(function() {
  $("#hfRemainingInstalls").bind('CheckBoxClicked', function(e) {    
     alert("checkbox clicked");       
  });
});

I am sure you have an ID problem. 我确定您有ID问题。 ASP.NET controls that reside inside of container elements such as UserControls and MasterPages, when rendered, have some junk prefixed to the id attribute to ensure uniqueness. 呈现在诸如UserControls和MasterPages之类的容器元素内部的ASP.NET控件在呈现时会在id属性前添加一些垃圾,以确保唯一性。 It is usually something like "ctl01_01_YourID" That said, you should probably be using the jQuery endsWith selector... 通常是类似“ ctl01_01_YourID”这样的内容,也就是说,您可能应该使用jQuery startsWith选择器...

$('input[id$=hfRemainingInstalls]').trigger('CheckBoxClicked');

The following will alert "true" if the element is found... 如果找到该元素,以下内容将发出“ true”警报...

alert($('#hfRemainingInstalls').length > 0);

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

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