开发者

How to bind this function to input focus

开发者 https://www.devze.com 2023-03-19 16:43 出处:网络
I have the following simplified function. Real usage removed. So, onfocus I expect the value of the textbox to be alerted.

I have the following simplified function. Real usage removed. So, onfocus I expect the value of the textbox to be alerted.

I would like to keep the function definition separate from the usage.

new function ($)
{
    $.fn.setFocus = function ()
    {
        alert($(this).val());
    }
} (jQuery);

My current attempt is not working:

$('input[type=tex开发者_运维知识库t]').focus(setFocus);

How can I get this to work? thanks.


setFocus is probably not defined. You should refer to the function itself, in this case $.fn.setFocus.

$('input[type=text]').focus($.fn.setFocus);


    $("input[type='text']").focus(function(){
alert($(this).val());
});

jQuery attribute selectors


What you probably want is this:

function setFocus() {
    alert($(this).val());
}

$("input[type='text']").focus(setFocus);

What you did by assigning setFocus to $.fn was create a plugin that would alert the contents of a selected element:

$("#foo").setFocus();

Supplying $.fn.setFocus to jQuery's focus call will technically work, but it has other effects that you likely don't want.


Your code looks more like it tries to extend the jQuery ..

Could it be that you want

new function ($)
{
    $.fn.setFocus = function ()
    {
        return this.focus(function(){
           alert($(this).val());
        });
    }
} (jQuery);

and call it like this

$('input[type=text]').setFocus();
0

精彩评论

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

关注公众号