歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Ajax 服務器返回html字符串中元素的事件綁定方法

Ajax 服務器返回html字符串中元素的事件綁定方法

日期:2017/3/1 10:29:15   编辑:Linux編程
寫代碼遇到一個糾結的問題,就是使用Ajax技術的時候,服務器返回的HTML字符串中元素的Jquery控制或者說是事件綁定方法失效,但是CSS控制是正常的,而如果不采用Ajax技術,則不會產生這樣的問題。後來終於發現,其實Jquery綁定事件的元素是當前頁面的元素,而采用Ajax技術後,服務器返回的HTML代碼中的元素隸屬於另一個頁面,此時其中的元素也當然不會被綁定事件。

我們來詳細看一下。我們平常為元素綁定事件是這樣做的,以我做的實驗為例:

在主頁面如main.php中加入

[javascript]
  1. <script type="text/javascript"
  2. src="<?php
  3. echo base_url ( "items/js/index/base_all.js" )?>"></script>
然後這個文件中的元素及可以用JS文件中的方法來控制了。假如說我的main.php有這樣一段代碼:

[php]
  1. <div class="product_photo"><a href=""><img
  2. src=<?php
  3. echo base_url ( $picture_path );
  4. ?> alt=""
  5. class="product_focus"></img></a></div>
我想控制img這個元素。並在base_all.js寫了這樣一段代碼:

[javascript]
  1. $(function() {
  2. $(".product_focus").bind(
  3. 'mouseover',
  4. function() {
  5. $(this).parent().parent().parent().parent().parent().children(
  6. '.product_display').css(
  7. {
  8. top : $(this).position().top + "px",
  9. left : $(this).position().left - 15
  10. + $(this).outerWidth(false) + "px"
  11. });
  12. $(this).parent().parent().parent().parent().parent().children(
  13. '.product_display').show();
  14. });
  15. $(".product_focus").bind('mouseleave', function() {
  16. $(".product_display").hide();
  17. });
  18. });
這樣就可以產生相應的鼠標移入移除的效果。

但是如果main.php中的這段代碼是Ajax服務器返回的,Jquery特效就不會起一點作用。

如:

[javascript]
  1. $.ajax({
  2. type:"POST",
  3. url:"<?php echo site_url("ajax_part/getProductDetail");?>",
  4. success:function(data)
  5. {$(".just").empty();
[javascript]
  1. $(".just").html(data);
  2. }
  3. });
其中data就是這段html代碼,就會不起效果。這大概就是我當初遇到的問題,其實細細想想解決這個問題其實不難,既然Jquery只能給當前頁面的元素綁定事件,那麼我們就可以在Ajax返回的HTML字符串載入到當前頁面後對其元素進行事件的重新綁定。方法就是這樣:

不用包含base_all.js這個JS文件,而把其中的Jquery控制代碼寫入$.ajax中。如下:

[javascript]
  1. $.ajax({
  2. type:"POST",
  3. url:"<?php echo site_url("ajax_part/getProductDetail");?>",
  4. success:function(data)
  5. {
  6. $(".just").empty();
  7. $(".just").html(data);
  8. afterLoad();
  9. }
  10. });
[javascript]
  1. function afterLoad()
  2. {
  3. $(function() {
  4. $(".product_focus").bind(
  5. 'mouseover',
  6. function() {
  7. $(this).parent().parent().parent().parent().parent().children(
  8. '.product_display').css(
  9. {
  10. top : $(this).position().top + "px",
  11. left : $(this).position().left - 15
  12. + $(this).outerWidth(false) + "px"
  13. });
  14. $(this).parent().parent().parent().parent().parent().children(
  15. '.product_display').show();
  16. });
  17. $(".product_focus").bind('mouseleave', function() {
  18. $(".product_display").hide();
  19. });
  20. }
將Jquery放在頁面載入Html字符串之後。為元素重新綁定事件就可以了。。
Copyright © Linux教程網 All Rights Reserved