简体   繁体   中英

Trigger element's onclick method with JQuery [ASP.NET]

I have an ASP.NET server control that inherits from CheckBoxList that renders the controls with a UL and LIs. The control is set to AutoPostBack.

Markup:

<div id="foo">
    <ul>
        <li>
            <input id="..." 
                   type="checkbox" 
                   name="ctl00$MainContent$FooList$0"    

                   onclick="javascript:setTimeout(
                   '__doPostBack(\'ctl00$MainContent$FooList$0\',\'\')', 0)" />

            <label ...>...</label>
        </li>
        ...
    </ul>
</div>

I would like to trigger the JavaScript that is rendered on the CheckBox when the parent LI is clicked. Here is what I have so far:

$("#foo li").click(function() {
    $(this).find("input:eq(0)").trigger("click");
});

This fires a postback in FF 3.x but the event handler in the codebehind is not fired. In IE 7 a script error comes up and the browser just kind of hangs there for a bit then reloads the page.

How should I be doing this?

I'd give this a try:

$("#foo li").click(function() {
    $(this).find("input:eq(0)").triggerHandler("click");
});

A trigger on a child will bubble to the parent, resulting in a loop in this case since the parent click is again firing the child click. Firefox sometimes recognizes and stops this, but the result is your box is checked, it bubbles, it's unchecked and so on postback, it's not firing because the check status really didn't change.

.triggerHandler() however won't bubble, and might resolve your issue (unless there's another script error occuring!). As a general rule, use this when triggering the handlers on a child, especially triggering the same event on the child that would bubble.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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