2016-07-28 235 views
1
<div id="user_addr"> 

    <!--- some dynamic content here, which is being loaded from db ---> 

<div class="add_address" > 
    <div class="error"></div> 
    <input type="hidden" id="addr_id" value="0"/> 
    <input type="text" id="usr_name" class="medium-input" placeholder="Enter Full Name" maxlength="50"/> 
    <input type="text" id="addr_line1" class="large-input" placeholder="Address Line 1" maxlength="100" /> 
    <input type="text" id="addr_line2" class="large-input" placeholder="Address Line 2" maxlength="100"/> 
    <input type="text" id="city" class="small-input" placeholder="City Name" maxlength="50"/> 
    <input type="text" id="state" class="small-input" placeholder="State Name" maxlength="50"/> 
    <input type="text" id="pincode" class="small-input" placeholder="Pin Code" maxlength="6"/> 
    <input type="text" id="phone" class="medium-input" placeholder="Mobile Number" maxlength="10"/> 
    <input type="submit" value="Save" class="save_address"/> 
</div> 


</div> 

我試圖重新加載/刷新div與編號usr_addr每當用戶單擊保存按鈕。使用jquery重新加載div內容

我使用

$('.save_address').click(function() { 
    alert('hi'); <--- doesn't prompt in second call 
    <!--- saving data to db ---> 
    $('#user_addr').load(location.href.replace('#', '') + ' #user_addr');// refreshing div to get latest saved data 
    } 

但是,對於第一次當我點擊Save,它工作正常,但DIV嵌套得到和源代碼,就成了

<div id="user_addr"> 
    <div id="user_addr"> <--- nested after function call 
     .... 
     .... 
     </div> 
    </div> 

而且,然後保存按鈕不起作用或無法調用js功能。任何人都可以建議解決這個問題?

回答

0

有些事情要解決這個問題:

$(document).on('click','.save_address',function() { // 1. use event delegation to be able to listen to .save_address element, whenever it's loaded via Ajax 
    var url = location.href.replace('#', '') + '#user_addr'; 
    console.log(url); // just to be sure 
    $.get(url, function(data){ // 2. perform an Ajax request to fetch your new content, and use a callback to handle the content 
    var data = $(data).find('#user_addr').html(); // 3. find the new content in the DOM 
    console.log(data); 
    $('#user_addr').html(data); // 4. insert it 
    }); 
}); 

希望這將有助於:)

注:我不會用一個input[type=submit]只要沒有form元素那裏,但我會使用button

+0

你是否遺漏了你的代碼中的任何東西,它不工作..即使我把'alert(data)'放在裏面,來檢查代碼流。但是,我沒有得到任何提示。 – Ravi

+0

在控制檯中,我得到了'TypeError:data.find不是函數'。 – Ravi

+0

難道你不想錯過回調參數嗎? $ .get(location.href.replace('#','')+'#user_addr',function(data){<<< – enguerranws

0

只要改變id="user_addr"id="user_addr_container'和JS來

$('#user_addr_container').load(location.href.replace('#', '') + ' #user_addr'); 
+0

如何將它從** location.href.replace('#','')+'#user_addr''加載到您剛剛要求**將id =「user_addr」更改爲id =「user_addr_container'** – Ravi