简体   繁体   中英

bind a click event only once for dynamically created elements

Updated: Fiddle Example

The code will dynamically create a text link via a select box. How would you bind a click event to it only once so that every dynamically created link will only add data to the table once. I have tried .one and one of the approaches from off but it isn't working.

Code:

 $(function (){
  $('.area').each(function(){
   var area = $(this),
       selectbox = area.find('select'),
       show = area.find('.show'),   
       dialog_open =  $(this).find(".dialog_open");


    selectbox.change(function(){
      selectbox = $(this).find('option:selected').text();
      show.html('<a href="#" onclick="javascript: return false" class="dialog_open">'+selectbox+'</a>')
    });

    var foo = function() {
    var dialog_open_text = $(this).find(".dialog_open").text();
      $('td').html(dialog_open_text);
    };

    show.on( "click",dialog_open, foo );

    show.off( "click", dialog_open, foo );

  });

});

HTML:

<div class="area">
    <select>
        <option>Choose</option>
        <option>One</option>
        <option>Two</option>
    </select>
    <div class="show">
    </div>
</div>

<div class="area">
    <select>
        <option>Choose</option>
        <option>One</option>
        <option>Two</option>
    </select>
    <div class="show">
    </div>
</div>

<table>
    <thead>
        <tr>
            <th>Title 1</th>
            <th>Title 2</th>
            <th>Title 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </tbody>
</table>

Change

show.on( "click",dialog_open, foo );

show.off( "click", dialog_open, foo );

to

show.one( "click",dialog_open, foo );

jsFiddle

jQuerys one will attach an event handler which will detach itself after being invoked once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM