2017-06-06 118 views
0

我有一些jquery選項卡,其中一些通過ajax加載。當第一次加載它們都沒問題時,事件會根據需要觸發一次,但當我點擊不同的選項卡然後返回到由ajax加載的選項卡時,jquery事件被觸發兩次,隨後加載該選項卡,添加另一個事件觸發器。似乎jquery一次又一次被加載,但是當我檢查chrome時,我只能看到它,所以我不知道發生了什麼。任何幫助,將不勝感激.. 下面是一個例子..重新加載jquery選項卡導致重複事件觸發

outerTabs.jsp

<html> 
<head> 
    <link rel="stylesheet" href="${pageContext.servletContext.contextPath}/resources/css/jquery-ui.css"> 
    <script type="text/javascript" src="${pageContext.servletContext.contextPath}/resources/js/jquery.js"></script> 
    <script type="text/javascript" src="${pageContext.servletContext.contextPath}/resources/js/jquery-ui.js"></script> 
    <script>var contextPath = "${pageContext.request.contextPath}";</script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      $("#outerTabs").tabs(); 
     }); 
    </script> 
</head> 
<body> 
    <div id="outerTabs"> 
     <ul> 
      <li><a href="#outerTab1">outerTab1</a></li> 
      <li><a href="${pageContext.servletContext.contextPath}/getTab2?param=param1">outerTab2</a></li> 
     </ul> 
    </div> 
    <div id="outerTab1"></div> 
</body> 
</html> 

tab2.jsp

<html> 
    <head> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $("body").on("click", "#link1", function(e) { 
      alert("clicked"); 
     }); 
    }); 
</script> 
    </head> 
<body> 
    <a id="return">return</a> 
    <div id="tab1"> 
     <a id="link1"> 
     link1 
     </a> 
    </div> 
</body> 
</html> 

控制器

@Controller 
public class Controller { 
@RequestMapping(value = { "/loadTabs" }, method = RequestMethod.GET) 
public ModelAndView loadTabs() { 
    ModelAndView model = new ModelAndView(); 
    model.setViewName("outerTabs"); 
    return model; 
} 

@RequestMapping(value = { "/getTab2" }, method = RequestMethod.GET) 
public ModelAndView getTab1(@RequestParam("param") String param) { 
    ModelAndView model = new ModelAndView(); 
    model.addObject("tab2Content", null); 
    model.setViewName("tab2"); 
    return model; 
} 
} 

所以在這個例子當我加載標籤2然後點擊回到標籤1,然後再次點擊標籤2時,點擊link1 lin k導致警報顯示兩次。

回答

1

您在每次重新加載時都給元素#link1再次點擊事件。您可以使用jquery-lib的http://api.jquery.com/off/來避免第二次提醒。 下面是一個例子:

$(document).ready(function() { 
    $("#link1").off("click").on("click", function(e) { 
     alert("clicked"); 
    }); 
}); 
+0

你爲此歡呼。我不得不限定每次打電話給我的實際項目,因爲我在身體上設置了多個呼叫事件,例如,你可以在多個..(「body」)中執行此操作。 off(「click」,「.editVicImage」)。on(「click」,「.editVicImage」,function(){..otherwise你關閉最後一個jquery方法的所有事件。 – user2554194

1

它沒有被加載的JQuery,但事件被重新綁定一遍又一遍。 一種選擇是有一個'is-bound'標誌。 如:

$("body").on("click", "#link1:not(.is-bound)", function(e) { 
     alert("clicked"); 
     $(this).addClass('is-bound'); 
    }); 

這樣,如果該元素沒有以前綁定的功能纔會觸發。

相關問題