mingfish_004
mingfish_004

Reputation: 1413

how to copy events to new elements?

how to copy events to new elements?

on document ready I bind many events to some elements , when add new elements , I want to copy the events to new, how to do ?

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<div class="box">
    <input type="text" name="a" value="a" />
    <input type="text" name="b"  value="b" />
</div>

<script type="text/javascript">
    function input_events(
        $('[name]').hover(
            function (){
                console.log(1);
            },
            function (){
                console.log(2)
            }
        ).focus(function (){
            //....
        }).blur(function (){
            //...
        }).tooltip(
            //..
        ).someEvent(
            //..
        )...

    );

    $(function(){
        input_events();
    });

    function bind_same_event_to_new(){
        $('<input type="text" name="c" value="c" />').appendTo('.box');
        // how to bind the input_events function to new input ?
    }

</script>

Upvotes: 0

Views: 88

Answers (1)

Jeff
Jeff

Reputation: 1800

the code below may help. anything created later with the specified selector will have all the events you need to define.

$('document).on('click', 'MY SELECTOR', function (e) {

    ... code here

    });

here's a fiddle: http://jsfiddle.net/6v8sh/2/

Upvotes: 1

Related Questions