解決使用jQuery採用append添加的元素事件無效的方法

來源:互聯網
上載者:User

標籤:

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){  $("button").live("click",function(){    $("p").slideToggle();  });});</script></head><body><p>這是一個段落。</p><button>請點擊這裡</button></body></html>

但是隨著jQuery的版本升級,自從jQuery 1.9及其以上已經無法使用live了,那麼沒有辦法了嗎,不是的,對於jQuery1.9版本及其以上可以使用on,其效果等同於live。下面的on的使用方法

<script>$(document).on("click", ".waiting-save", function () {  $(this).html(‘@T("Saving...")‘)  $(this).attr("disabled", "");});</script>

整個代碼例子為:

<!DOCTYPE html><html><head>    <title></title>    <meta charset="utf-8"/></head><body><div>   <form action=" " method=" " >    <div class="list">        <div class="addList">            分部:            <select>                <option>分部</option>                <option>分部1</option>                <option>分部2</option>            </select>            數量:<input type="text" value="123"/>            <!-- <span class="add">添加</span>  -->
             <input type="button" value="添加"  class="add"/>        </div>    </div>    </form></div></body><script type="text/javascript" src="./js/jquery-2.1.4.min.js"></script><script type="text/javascript">    $(function(){        //全域變數i          i=0;          $(".add").click(function() {              $(".list").append(function(){                    return ‘<div class="delList‘+i+‘"> 分部: <select><option>分部</option><option>分部1</option><option>分部2</option></select> 數量:<input type="text" value="123"/><input type="button" class="del" value="刪除"/> </div>‘;              });              i++;          });         $(document).on("click", ".del", function () {            $(this).parent().remove();         });    })</script></html>
注意:
1.button的問題
<input type="button" value="添加" class="add"/>
這句不能使用 <button class="add">添加</button>
使用button標籤的時候,添加的 delList DIV會閃一下,閃了之後就會消失了,不能顯示在頁面上。
2.input標籤閉合問題。
在編輯頁面的時候,要記得標籤要閉合,不閉合的話,會出現問題。

參考網址:
http://so.xiaohuihui.net/?a=url&k=6c98d343&u=aHR0cDovL3d3dy5idWJ1a28uY29tL2luZm9kZXRhaWwtNTcwMjgyLmh0bWw=&[email protected]qL5Lu25peg5pWI55qE5pa55rOVIA==&s=anF1ZXJ5IGFwcGVuZCDml6DmlYg=

解決使用jQuery採用append添加的元素事件無效的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.