jQueryUI - Accordion - Setting ID from a href

jQueryUI - Accordion - Setting ID from a href

本文关键字:href from Setting Accordion jQueryUI ID      更新时间:2023-09-26

首先感谢所有在本网站上提供输入的人。它极大地帮助了我找到问题的答案。这是我在这里的第一篇帖子,希望有人能引导我朝着正确的方向前进。

我目前正在一个网站上工作,试图设置一个相当大的手风琴设置(30多个手风琴)。我一直在寻找答案,找到了这个页面,它提供了很好的信息,以及我正在努力完成的事情。

ID是根据<h3>标签。我有一个相当长的<h3>因为我正在从数据库中提取事件的缩写和描述。(例如:AAM-服装及配饰营销系列)。我可以让它工作,但ID应该是"aam__apparel"之类的。。。等

我需要能够将ID创建为a href="#myNameHere"中的#之后的任何ID,这将只是缩写。(缩写和描述需要在h3中显示)

<div id="accordion">
<h3><a href="#link1">Link1</a></h3>
<div>content</div>
</div>

如果您将"Link1"更改为"Link1Test",则会将ID更改为"Link1Test"。

$(function() {
  var $accordion = $("#accordion").accordion({active: false, collapsible: true}),
  hashId = 0;
if (window.location.hash) {
  $accordion.children('h3').each(function(i){
    var txt = $(this).text().toLowerCase().replace(/'s+/g,'_');
    this.id = txt;
    if (txt === window.location.hash.slice(1)) {
      hashId = i;
    }
  });
  $accordion.accordion({
    active: hashId,
    animate: true,
    heightStyle: 'content',
    collapsible: true,
    create: function( event, ui ) {
      $accordion.children('h3').each(function(i){
        $(this).before('<a class="accordion-link link" data-index="' + i + '" href="#' + this.id + '"></a>');
      });
      $accordion.find('.accordion-link').click(function(){
        $accordion.accordion( "option", "active", $(this).data('index') );
      });
    }
});
}
});

感谢您的帮助和插话,非常感谢您的时间和知识。

锚点的href属性是根据标头的id属性设置的;这些CCD_ 3是从第一个CCD_ 5调用中的CCD_。因此,这就是我们想要编辑的内容,我们可以在预设的分隔符上使用.indexOf来提取前几个字符:

  var DELIMITER = '_-_';
  $accordion.children('h3').each(function(i){
    var txt = $(this).text().toLowerCase().replace(/'s+/g,'_');
    txt = txt.slice(0, txt.indexOf(DELIMITER)); // <- extracts Abbreviation
    this.id = txt;
    if (txt === window.location.hash.slice(1)) {
      hashId = i;
    }
  });

这假设您的所有标题都遵循"缩写-描述"模式。如果是不同的模式,只需更改DELIMITER值即可。(如果你不介意后面的下划线,也可以只是DELIMITER = "-"

现在,如果有多个模式,您可以将.slice调用拆分为多个条件,或者使用正则表达式将它们全部组合起来:

  var DELIMITERS = ["_-_", "_:_"]; // <- backslash-escape special characters here
  // and then...
    txt = txt.replace(new RegExp("(" + DELIMITERS.join("|")) + ").*"), "");

在描述中有多个DELIMITER实例是安全的,因为.indexOf和regex匹配都将返回第一个实例。由于这是在任何地方实际使用之前编辑txt,因此它应该与代码的其余部分兼容