开发者

jquery plugin: How can i run my function so that "this" refers to the element the plugin was called from?

Fairly basic question i'm hoping. In the following javascript, I want to run the checkval() function as if it were executed in the scope of which "this" (within the checkval) refers to the element that the plugin is being called on (well, one of the elements).

So if i called

$('.has_hidden').conditional(); 

Then that would run the checkval on all those items as well as binding it to the on change event.

Reason is, I have a form, which will unhide further options if you type in something, say if you type in "australia" it will unhide a bunch of other elements. Now when I save and reload that form, my php script repopulates the data, but the other elements remain hidden. I just need to run check val so they get un hidden. Ming Bai Ma

/**
 * This class will show or hide a bunch of elements (A,B,C) based on the value in element (E, this).
 * To use it, take the name of the form element (E, this) and apply it as a class to A,B,C
 * Then add a display none to A,B,C (add class off)
 * Set the "rel" tag on 
 * Finally, run $(E).conditional();
 */
(function( $ ){
    $.fn.conditional = function() {
    return this.each(function(){
        var $this = $(this);
        $this.unbind('change.cns').bi开发者_StackOverflow社区nd('change.cns', checkval);
    });
    function checkval(){
        var regex = $(this).attr('rel');
        var class_name =$(this).attr('name');
        if($(this).val().search(regex)>-1) 
        $('.'+class_name).show();
        else
        $('.'+class_name).hide();
    }   
    };
})( jQuery );


I think you can use the jquery proxy in this case to solve this issue:

$this.unbind('change.cns').bind('change.cns', checkval);

To

$this.unbind('change.cns').bind('change.cns', $.proxy( checkval, $this ));


Sorry I didn't explain my question properly, but what I was actually looking for was

$this.trigger('change.cns');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜