简体   繁体   English

jquery-ui,已添加选项卡,无法通过新选项卡上的文本链接切换至旧选项卡

[英]jquery-ui, added tab, cannot switch to older tab via text link on new tab

I have spent many hours researching this problem to no avail. 我花了很多时间研究这个问题,但无济于事。 I have a simple page with 3 tabs. 我有一个带有3个标签的简单页面。 Tab #1 has a button to add a new tab (tab #4). 选项卡#1具有一个用于添加新选项卡的按钮(选项卡#4)。 Tab #2 has a hyperlink to switch to tab #3 which works fine (also get console message). 选项卡#2具有可切换至选项卡#3的超链接,该超链接工作正常(也可获取控制台消息)。 After adding tab #4 (index=3), via button, which includes a hyperlink to switch to tab #3, the hyperlink on tab #4 is not functional nor is there a console message. 在添加选项卡#4(index = 3)后,通过按钮(其中包括一个可切换到选项卡#3的超链接),选项卡#4上的超链接不起作用,也没有控制台消息。

 function addTab4() { $("#btnAdd").attr("disabled","disabled").text("tab 4 added"); $("#tabs").find(".ui-tabs-nav").append('<li><a href="#tabs_4">4</a></li>'); $("#tabs").append("<div id='tabs_4'></div>"); $("#tabs_4").html("<a id='selectTab3' href='#tabs_3'>goto tab 3</a>"); // doesn't switch to tab 3 $("#tabs").tabs("enable"); $("#tabs").tabs("refresh"); return false; }; $(document).ready(function(){ $("#tabs").tabs(); $("#tabs").tabs("option", "active", 0); $("a#selectTab3").click(function() {//works from an original tab, not added tab console.log("a#selectTab3 clicked"); $("#tabs").tabs("option", "active", 2); }); $("#btnAdd").click(function() { addTab4(); }); }); 
 <div id="tabs"> <ul> <li><a href="#tabs_1">1</a></li> <li><a href="#tabs_2">2</a></li> <li><a href="#tabs_3">3</a></li> </ul> <div id="tabs_1"> One<br> <button id="btnAdd">Add Tab 4</button> </div> <div id="tabs_2"> Two<br> <a id="selectTab3" href="#tabs_3">goto tab 3</a> <!-- works --> </div> <div id="tabs_3"> Three </div> </div> 

Thanks in advance! 提前致谢!

The problem with your code is that you have dynamically generated the anchor element. 代码的问题在于,您已经动态生成了anchor元素。 So, the click event you have designated for the anchor will not work for the newly created event. 因此,您为锚点指定的click事件将不适用于新创建的事件。 To tackle that you need to Understand & Use Event Delegation . 为了解决这个问题,您需要了解并使用事件委托 So instead of the previous event handler use this instead and you will be fine, 因此,您可以使用以前的事件处理程序代替以前的事件处理程序,

 $(document).on("click","a.selectTab3",function() {
        console.log("a#selectTab3 clicked");
        $("#tabs").tabs("option", "active", 2);
    });

And here is the working fiddle 这是工作的小提琴

PS PS

You are attempting to use multiple id with the same name which is a very bad practice as id must be unique in the DOM. 您正在尝试使用具有相同名称的多个id,这是一个非常糟糕的做法,因为id在DOM中必须唯一。 So, I have changed it to instead use class . 因此,我将其更改为改为使用class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM