jQuery -错误的技术或错误

jQuery - Wrong technic or a bug

本文关键字:错误 技术 jQuery      更新时间:2023-09-26

我有一个HTML页面,我想根据jQuery手风琴的选定元素更改H3标记的文本。在这个链接有一个小的演示。

<div id="acc1" class="basic">
    <h3><a href="#">aaa</a></h3>
    <div></div>
    <h3><a href="#">bbb</a></h3>
    <div></div>
    <h3><a href="#">ccc</a></h3>
    <div></div>
</div>
<h3 class="ui-widget-header">xyz</h3>
$(document).ready(function () {
    $("#acc1").accordion({
        heightStyle: "fill",
        active: false,
        autoheight: false,
        collapsible: true,
        alwaysOpen: false,
        activate: function (event, ui) {
            var idx = $("#acc1").accordion("option", "active");
            var txt = $("#acc1 > h3:nth-child(" + (idx + 1) + ") > a").text();
            $("h3.ui-widget-header").text((idx + 1) + " ---> " + txt);
        }
    });
});

acc1在开始时被折叠,很快一个元素被单击,jQuery函数读取其文本并将其分配给H3标记。但只是第一次点击,页面加载后,工作良好。在此之后,只分配了错误的值。

我这样做是错误的还是jQuery有bug ?

使用的东西:jQuery v1.9.0, jQuery UI v1.9.2

问候,grafl

我的解决方案是:

$(document).ready(function () {
    $("#acc1").accordion({
        heightStyle: "fill",
        active: false,
        autoheight: false,
        collapsible: true,
        alwaysOpen: false,
        activate: function (event, ui) {            
        }
    });
    $("h3").click(function(){    
        var txt = $(this).find('a').text(); 
        $(".ui-widget-header").html(txt);  
    });
});
<<p> JSFIDDLE演示/strong>

:nth-child考虑所有兄弟,而不仅仅是匹配您所限定的标记的那些。因此,h3:nth-child(2)(例如)意味着"h3元素也是其父元素中的第二个子元素",而不是"其父元素中的第二个h3元素"。

对于后者,您可以使用jQuery的伪选择器:eq(它使用基于0的索引)或.eq函数(它也这样做)。

改变这一行:

var txt = $("#acc1 > h3:nth-child(" + (idx + 1) + ") > a").text();

:

var txt = $("#acc1 > h3").eq(idx).children("a").text();

更新小提琴

或:

var txt = $("#acc1 > h3:eq(" + idx + ") > a").text();

更新小提琴