开发者

jquery: How can I trigger click() without editing the element state?

开发者 https://www.devze.com 2022-12-28 18:58 出处:网络
I need to trigger a click function assigned to a checkbox, but without actually changing it\'s checked state (which click() does).

I need to trigger a click function assigned to a checkbox, but without actually changing it's checked state (which click() does).

Scenario: I have a form with several checkboxes that when selected reveal a textarea. This works fine, but I also need to cal开发者_运维技巧l the click() function on $(document).ready()

My code is below, please note I have very limited access to changing the generated html. I have an object (admin_panels) which will store each checkbox and the texarea it should bring up.

var admin_panels = {"checkbox-id" : "textarea-id"};

$(document).ready(function(){
for (var elem in admin_panels) {
    $("#" + elem).click(admin_slide);
    // $("#" + elem).click();
}
})
function admin_slide() { 
    if ($(this).is(":checked")) {
        $("#" + admin_panels[this.id] + "-wrapper").slideDown();
  }else{
        $("#" + admin_panels[this.id] + "-wrapper").slideUp();
    }
}

Thanks


If you want to call the admin_slide function for an element, you can do this:

admin_slide.call(domElement);

The value of this within the admin_slide function will be set to domElement.

In this case, domElement could be $('#'+elem)[0] or document.getElementById(elem).

Edit:

Another way to do this, using jQuery methods exclusively, is: $(selector).each(admin_slide). So your code could be:

for (var elem in admin_panels) {
    $("#" + elem).click(admin_slide)
                 .each(admin_slide);
}


To prevent the checkboxes states from changing, include event.preventDefault in your event handler code. That with interjay's answer will look like this:

$("#" + elem).click(function(event) {
    event.preventDefault();
    admin_slide.call(this);     
});

The only bad thing about this approach is that the checkbox's state is changed when admin_slide() is called, but gets changed back after that. You can work around that easily enough by changing what happens in your admin_slide function.

function admin_slide() { 
    if ($(this).is(":checked")) {
        $("#" + admin_panels[this.id] + "-wrapper").slideUp();
    }else{
        $("#" + admin_panels[this.id] + "-wrapper").slideDown();
    }
}


So, you are assigning the click function in the document.ready? Why not just call admin_slide directly in addition to assigning the event handler?

0

精彩评论

暂无评论...
验证码 换一张
取 消