使用jquery重新加载div内容

时间:2016-07-28 10:26:20

标签: javascript jquery html

<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,其ID为usr_addr

我正在使用

 $('.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功能。有人可以建议解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

只需将id="user_addr"更改为id="user_addr_container',将js更改为

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

答案 1 :(得分: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