JSFiddle - React, Tailwind, and code Playground
HTML
<h1>This is My Nifty Feature</h1>
<div id="myFeature">
<ul class="sections">
<li>
<h2><a href="/section/1">Section 1</a></h2>
<ul>
<li>
<h3><a href="/section/1/content/1">Section 1 Title 1</a></h3>
<p>The excerpt content for Content Item 1</p>
</li>
<li>
<h3><a href="/section/1/content/2">Section 1 Title 2</a></h3>
<p>The excerpt content for Content Item 2</p>
</li>
<li>
<h3><a href="/section/1/content/3">Section 1 Title 3</a></h3>
<p>The excerpt content for Content Item 3</p>
</li>
</ul>
</li>
<li>
<h2><a href="/section/2">Section 2</a></h2>
<ul>
<li>
<h3><a href="/section/2/content/1">Section 2 Title 1</a></h3>
<p>The excerpt content for Content Item 1</p>
</li>
<li>
<h3><a href="/section/2/content/2">Section 2 Title 2</a></h3>
<p>The excerpt content for Content Item 2</p>
</li>
<li>
<h3><a href="/section/2/content/3">Section 2 Title 3</a></h3>
<p>The excerpt content for Content Item 3</p>
</li>
</ul>
</li>
<li>
<h2><a href="/section/3">Section 3</a></h2>
<ul>
<li>
<h3><a href="/section/3/content/1">Section 3 Title 1</a></h3>
<p>The excerpt content for Content Item 1</p>
</li>
<li>
<h3><a href="/section/3/content/2">Section 3 Title 2</a></h3>
<p>The excerpt content for Content Item 2</p>
</li>
<li>
...
CSS
#section_nav li,
#item_nav li{
color: #06c;
cursor: pointer;
text-decoration: underline;
}
#content{
padding: 10px;
background: #ffc;
}
JavaScript
var myFeature = {
'config': {
// 默认的容器是 #myFeature
'container': $('#myFeature')
},
'init': function (config) {
// 自定义配置可以init的config参数配置
if (config && typeof (config) == 'object') {
$.extend(myFeature.config, config);
}
// 创建 或者 缓存dom元素。这些元素在后续代码中使用
myFeature.$container = myFeature.config.container;
myFeature.$sections = myFeature.$container.
// 仅选择直接子元素
find('ul.sections > li');
myFeature.$section_nav = $('<p/>')
.attr('id', 'section_nav')
.prependTo(myFeature.$container);
myFeature.$item_nav = $('<p/>')
.attr('id', 'item_nav')
.insertAfter(myFeature.$section_nav);
myFeature.$content = $('<p/>')
.attr('id', 'content')
.insertAfter(myFeature.$item_nav);
// 构建一级导航,并且触发第一个列表元素的点击事件
myFeature.buildSectionNav(myFeature.$sections);
myFeature.$section_nav.find('li:first').click();
// 隐藏原始的HTML代码
myFeature.$container.find('ul.sections').hide();
// 设定属性initialized标识对象已被初始化。本例中没有用到,但这是一个很方便的属性
myFeature.initialized = true;
},
'buildSectionNav': function ($sections) {
// 迭代区域的列表项
$sections.each(function () {
// 获取当前区域引用
var $section = $(this);
// 创建一级导航列表项
$('<li/>')
// 使用h2的文本作为导航项的标题
.text($section.find('h2:first').text())
// 将此列表项添加到一级导航元素下
.appendTo(myFeature.$section_nav)
// 使用data属性在新创建的列表项上存储一个到原始区域的引用
.data('section', $section)
// 为此列表项创建点击回调函数
.click(myFeature.showSection);
});
},
'buildItemNav': function ($items) {
// 迭代区域内容项
$items.each(function () {
// 当前内容项的引用
var $item = $(this);
// 创建一个列表项元素
$('<li>')
//...