仅为动态创建的元素绑定一次click事件

时间:2014-05-26 15:42:49

标签: javascript jquery html onclick

更新: Fiddle Example

代码将通过选择框动态创建文本链接。如何将click事件仅绑定到它一次,以便每个动态创建的链接只会向表中添加一次数据。我尝试了.one和来自off的其中一种方法,但它无效。

代码:

 $(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>

1 个答案:

答案 0 :(得分:1)

更改

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

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

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

jsFiddle

jQuerys one将附加一个事件处理程序,它将在调用一次后自行分离。