2017-03-02 31 views
0

我有一個模式。在點擊我加載一些元素到一個ul列表模式的內容。函數.on不會爲以後生成的元素工作

這個函數是通過類「modaldata」調用的,對於我以後生成的元素,這個函數什麼都不做,我不知道爲什麼?

多數民衆贊成在炫魅

$(".modaldata").on("click",function(){ 
alert("klick"); 
    var modalid = $(this)[0].getAttribute("data-modalid"); 
    var ds = $(this)[0].getAttribute("data-ds"); 
    var step = $(this)[0].getAttribute("data-step"); 
    $.ajax({ 
     type: "POST", 
     url: "'.$global['serverurl'].'/system/modalcontent.php", 
     data: { modalid : modalid, ds : ds, step: step }, 
     success: function(result){ 
      var res = $.parseJSON(result); 
      eval(res.js)}, 
     error: function(){ 
       alert("failure:"+res.msg); 
     } 
    }); 
}); 

那部分從模式modalcontent.php 它會顯示正確,但如果我點擊在<span class="modaldata"部分

... $cont.='<li class="list-group-item li_'.$e['DS'].'"> <span class="modaldata" data-id="'.$e['DS'].'" data-step="edit" data-modalid="rollenverw"><i class="fa fa-wrench"></i> '.$e['ROLE_BEZ'].'</span><span class="badge badge-success"> '.$tmp['count'].' </span>'.$tmp['del'].'</li>'; 
    } 
    $res['js'].='$("#ex_roles_div ul").append("'. preg_replace('/\r|\n/', '', addslashes($cont)).'");'; 
功能不會再在裏面工作的功能

echo json_encode($ res);

調出功能

<a href="#" class="modaldata" data-ds="'.$e2['DS'].'" data-modalid="changerole" data-target="#modal_changerole" data-toggle="modal">'.GloFu_get_rolename($e2['USER_HOME'],$e2['ROLE']).'</a> 
+0

抱歉,您的意思是什麼 – newbieRB

+0

您能否構建一個重現該問題的片段?如果我們看到實際的代碼,幫助你會容易得多... –

+0

請永遠不要*,永遠**使用'eval()'。這實際上是你在JS代碼中可以做的最糟糕的事情。還要注意,你可以使用'data()'而不是'getAttribute':'var modalid = $(this).data('modalid');' –

回答

0

您需要綁定的模式,並第一次調用單擊位爲dinamically添加的元素不同(事件代表團):

$(document).on("click", ".modaldata", function() { 
    alert("klick"); 
    var modalid = $(this)[0].getAttribute("data-modalid"); 
    var ds = $(this)[0].getAttribute("data-ds"); 
    var step = $(this)[0].getAttribute("data-step"); 
    $.ajax({ 
    type: "POST", 
    url: "'.$global['serverurl'].'/system/modalcontent.php", 
    data: { 
     modalid: modalid, 
     ds: ds, 
     step: step 
    }, 
    success: function(result) { 
     var res = $.parseJSON(result); 
     eval(res.js) 
    }, 
    error: function() { 
     alert("failure:" + res.msg); 
    } 
    }); 
}); 

你可以閱讀更多關於這個here

+0

哦,似乎「$(document).on(」click「,」.modaldata「,」這是重要的差異,但我真的不明白我的第一個代碼之間的區別... – newbieRB

+0

@newbieRB,變化(「click」,function(){'to'$(document).on(「click」,「.modaldata」,function(){'。我也是從$(「。modaldata」在我的回答中張貼了一個鏈接,您可以在這裏閱讀更多關於活動委派的信息,我希望它能幫助你 – Ionut