【问题标题】:bind a click event only once for dynamically created elements只为动态创建的元素绑定一次点击事件
【发布时间】:2014-05-26 15:42:49
【问题描述】:

更新:Fiddle Example

代码将通过选择框动态创建文本链接。您将如何将单击事件仅绑定一次,以便每个动态创建的链接只会将数据添加到表中一次。我已经尝试过.oneoff 中的一种方法,但它不起作用。

代码:

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

【问题讨论】:

    标签: javascript jquery html onclick


    【解决方案1】:

    改变

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

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

    jsFiddle

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

    【讨论】:

    • 我想我表达得不够明确。当其他动态创建的元素替换旧元素时,这将不起作用。
    • @user35295,当点击替换旧元素的动态元素时,您希望发生什么?它还应该更改文本吗?
    • 是的。我希望新的也有一键事件功能。他们还将更改文本一次。
    • 我不确定我是否理解,在我提供的小提琴中,这就是发生的事情。元素被创建并且函数只运行一次,即使你将链接从“一”更改为“二”
    • 也许因为两个相同的选择框,我的原始示例无法理解这一点。你能再检查一下这个新的 [fiddle] (jsfiddle.net/XCfAQ/22)。您单击“1”并更改文本,然后当您选择“2”并单击它时,表格中的文本是否会更改?我想将one点击功能应用于“1”,然后当我将其更改为“2”时恢复点击功能
    猜你喜欢
    • 2013-07-07
    • 2020-09-29
    相关资源
    最近更新 更多