[英]Reloading div content using jquery
<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. 每当用户单击“保存”按钮时,我正在尝试使用id
usr_addr
重新加载/刷新div
。
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 但是,当我第一次单击“
Save
,它工作正常,但div嵌套并在源代码中,它变为
<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. 然后,保存按钮不起作用或无法调用js功能。 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
注意:我不会使用
input[type=submit]
,只要那里没有form
元素,但我会使用一个button
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.