动态创建切换链接可见性的按钮

时间:2014-09-14 17:23:45

标签: jquery html

我有一个链接列表:

<ul>

<li class='season1'>season1 episode1</li>
<li class='season1'>season1 episode2</li>
<li class='season1'>season1 episode3</li>
<li class='season1'>season1 episode4</li>
<li class='season1'>season1 episode5</li>

<li class='season2'>season2 episode1</li>
<li class='season2'>season2 episode2</li>
<li class='season2'>season2 episode3</li>
<li class='season2'>season2 episode4</li>
<li class='season2'>season2 episode5</li>

<li class='season3'>season3 episode1</li>
<li class='season3'>season3 episode2</li>
<li class='season3'>season3 episode3</li>
<li class='season3'>season3 episode4</li>
<li class='season3'>season3 episode5</li>

</ul>

我可以使用jQuery生成按钮来切换类以仅显示特定的季节吗?

2 个答案:

答案 0 :(得分:0)

是的,只需隐藏所有链接,只显示特定季节的链接。 e.g。

$("[class^='season']").hide();
$(".season2").show();

您必须将此绑定到某个按钮或链接。

创建链接&amp;结合:

$("ul li").each(function (i, e) {
    if ($("button." + e.className).length) return; // Already exists

    var $button = $("<button>").addClass(e.className).html(e.className);
    $button.click(function () {
        $("li").hide();
        $("li." + this.className).show();
    });
    $("body").append($button);
});

JSFiddle:http://jsfiddle.net/o656mbnL/

答案 1 :(得分:0)

我们在HTML中添加一些按钮:

<button id="season1">Season 1</button>
<button id="season2">Season 2</button>
<button id="season3">Season 3</button>
<!-- Existing code here -->

现在,使用jQuery,您可以在每次单击按钮时触发一个函数:

function show(season) {
    $("ul > li").hide();
    $("ul > ." + season).show();
}

$("#season1").click(function () {
    show("season1");
});

$("#season2").click(function () {
    show("season2");
});

$("#season3").click(function () {
    show("season3");
});