开发者

dynamic variable in event bind

I'm having a problem binding a dynamic event in jQuery. What I want to achieve is to have an event that acts on a variable that has previously been set. For example I have

someFunc = function (form_id)
{
    $("input").bind("focus", function ()
    {
        $("#"+form_id).css({"border":"1px solid red"});
    });
}

someFunc("edit_form");
somefunc("add_form");

Now this is a large simplification of what I'm looking to do but the dynamic nature of a variable when binding is what I need. The problem here is that essentially I want jQuery to execute on whatever "form_id" was when the bind was applied but instead it will execute on whatever the "form_id" is when the focus is triggered.

I understand why this occurs, my question is how can I achieve the functionality I'm looking for. (Again form here is just an example, not an actual bit of functionality).

Edit 1:

This is probably a better example of what I'm trying to achieve:

Dog.prototype = {
    name: "Dog",

    bind_function : function ()
    {
        name = this.name;

        $(name+"_edit_form input[name='something']").bind("focus", function ()
开发者_如何学Go        {
            console.log(name);
        })
    }
}

function Dog() {
    this.breed = "Chihuaha";
}

Rover = new Dog();
Rover.bind_function();

Fido = new Dog();
Fido.bind_function();

Now I want focus to produce a console log of that particular dogs name, but at present it will just console log the last dog's name?


I was looking for eventData to pass variables at the time of binding rather than execution. About halfway down the jQuery documentation page for bind():

http://api.jquery.com/bind/


I think this is what you're after?

$("form").each(function() {
    var id = $(this).attr("id");
    $("input", $(this)).bind("focus", function ()
    {
        var border = "";
        switch (id) {
            case "edit_form":
                border = "1px solid red";
                break;
            case "add_form":
                border = "1px solid blue";
                break;
        }

        $(this).css( { border: border });
    });
});

Although not using your function, it will assign different CSS based on the focused element form ID.

Live test case.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜