切换DIV取决于选择哪一个


 var header = $("#accordion");
            $.each(data, function () {
                header.append("<a id='Headanchor' href='javascript:toggleDiv($(this));'>" +   this.LongName + "</a>" + "<br />",
                "<div id='myContent' style='display:none'>" +
                "<ul>" +
                "<li>" + "ID: " + this.Id + "</li>" +
                "<li>" + "Short Name: " + this.ShortName + "</li>" +  "</ul>" + "</div>"
                );

                function toggleDiv(element) {
       var x = element.next();
       x.toggle();
       <div id="accordion">
</div>

只有一个Div的工作脚本即

function toggleDiv() {
              $("#myContent").toggle();
}

我想根据单击哪个锚固标签,但无法执行此操作。如果我使用ID选择器,则第一个Div会被切换,但没有其余的,因为它们获得了相同的ID,它是Erong。

javascript:toggleDiv($(this))中的 this中指向窗口,而不是对象。见JS小提琴。因此,在下面更改代码:

"<a id='Headanchor' href='javascript:toggleDiv($(this));'>"

to:

"<a id='Headanchor' href='#' onclick='return toggleDiv($(this));'>"

和JS代码:

function toggleDiv(element) {
       var x = element.next();
       x.toggle();
       return false;
}

此外,ID应该是唯一的,在您的代码中,您将具有多个大型元素元素。

隐藏全部,只显示您想要的方法:

$('#accordian>div').hide()      // hide all divs within the accordian
  .find('#selectedId').show();  // then show the one that matches the ID you want

,但要节省重新发明方向盘并使用jqueryui的麻烦。

最新更新