<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>
I'm trying to reload/refresh div
with id usr_addr
whenever user click save button.
I'm using
$('.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
}
But, for the first time when I click Save
, it works fine, but div gets nested and in the source code, it becomes
<div id="user_addr">
<div id="user_addr"> <--- nested after function call
....
....
</div>
</div>
And, then save button doesn't work or unable to call js function. Could anyone suggest solution for this issue ?
只需将id="user_addr"
更改为id="user_addr_container'
并将js更改为
$('#user_addr_container').load(location.href.replace('#', '') + ' #user_addr');
Some things to fix this :
$(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
});
});
Hope this will help :)
NB: I wouldn't use a input[type=submit]
as long as there is no form
element there, but I would use a button
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.