jquery - 如何在jquery中编写快速切换列表?

标签 jquery toggle

我想向我的网站添加切换属性。当我单击隐藏/显示按钮时,它应该显示/隐藏 div。按照字母顺序,用户点击某个字母就会显示以该字母开头的内容。所以我的代码在这里:

<script>
$(document).ready(function() {
    $('#button_letter_A').click(function() {
        $('#portfolio_item_A').toggle();

    });
     $('#button_letter_B').click(function() {
        $('#portfolio_item_B').toggle();
    });
});
</script>

而不是按顺序写下所有字母;如何快速编写这段代码。例如;我可以用 JavaScript 中的 for 循环来实现吗?

最佳答案

// target everything with IDs that start with 'button_letter'
$("[id^='button_letter']").click(function () {

    // split the letter out of the ID
    // of the clicked element and use it to target
    // the correct div
    $("#portfolio_item_" + this.id.split("_")[2]).toggle();
});

引用:

关于jquery - 如何在jquery中编写快速切换列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10567113/

相关文章:

javascript - jQuery:删除文本区域中的字符串一次?

javascript - jQuery 切换自定义动画

javascript - 在 javascript 代码中编写 html

javascript - React 中的多个状态变化

javascript - 为什么这个 jQuery 点击功能不起作用?

javascript - 单击另一个 div 时更改(切换)css

javascript - JQuery 切换/html : changing the content in div

jquery - 在 .toggle() 之后,用户在 jQuery 中使用 .mouseleave() 后单击两次

javascript - 无法初始化 fastclick 插件

javascript - 数据表更改默认排序顺序