jquery添加的html元素按鈕爲何不執行類樣式綁定的click事件

代碼舉例:jquery

更多按鈕:ajax

<input type="button" class="addMore" id="addMore${issue.id }" value="更多" />json

點擊按鈕添加一行文本框和「提交」按鈕:(沒有問題,能夠正常添加)服務器

$(".addMore").click(function(){app

        var index = this.id.substring(7,this.id.length);post

        //$("#tr"+index).clone().appendTo("#table"+index);this

        $("#table"+index).append("<tr><td></td>"+url

       " <td><input id='content'"+num + " type=text  size=60/></td>"+spa

        "<td><input id='date'"+num +" type=text /></td>"+事件

        "<td><input id='result'"+num+" type=text /></td>"+

        "<td><input type=button class='submitBtn' id='addBtn'"+index +" value='提交'/></tr>");

 });

全部「提交」按鈕的點擊事件:

      $(".submitBtn").click(function(){//初始化後添加的jQuery元素的click事件

         //議題的編號,也是text的index

         var index = this.id.substring(6,this.id.length);

         alert("index="+index);

         var content = $("#content"+index).val();

         var date = $("#date"+index).val();

         var result = $("#result"+index).val();

         //判斷是否有空值

         if(content.length != 0 && date.length != 0 && result.length != 0 ){

             $.ajax({

                 url:"addIssueInfo",

                 type:"post",

                 data: {issueContent:content,

                         issueId:index,

                         issueDate:date,

                         issueResult:result},

                 datatype: "json",

                 success:function(){

                     alert("添加成功!");

                     $tr = $("#addBtn"+index).parent("td").parent("tr");

                     $tr.remove();

                     //追加行

                     $("#table"+index).append("<tr><td></td><td>"+content+"</td><td>"+date+"</td><td>"+result+"</td><td></td></tr>");           

                 },error:function(){

                     alert("服務器忙,請稍候再試!");

                 }

             });

         }else{

             alert("對不起,當前行的每一條信息均不能爲空,請補全後提交!");

         }

    }); 

問題是,爲何點擊「更多」觸發的事件添加的文本框和「提交」按鈕,這個按鈕不執行class="submitBtn"的點擊事件?

 

解決:在添加更多一行的時候所產生的 input 和 button 都是動態生成的,因此不能使用 click,要使用 live (jquery 1.7.2 以後的版本不建議使用 live) 或 on

把$(".submitBtn").click(function(){
改成
$(".submitBtn").live('click', function(){
或者
$(".submitBtn").on('click', function(){

記住若是元素在頁面初始化的時候不存在,而是以後經過動態生成在頁面中的,要對這些元素進行操做,例如 click, blur, keyup, change....,都要使用 on

.on('click', function
.on('blur', function
.on('keyup', function
....
相關文章
相關標籤/搜索