0

我正在尝试使下拉列表用作页面上的过滤器。我已经创建了表单,并且锚点在那里,当您单击下拉项目时什么都没有发生。如何触发它链接到锚点?

这是我使用的 jQuery:

<script>
$("#portfolio-list").bind("change", function() {
    $("#" + this.value).show();
    $("p:not(#" + this.value + ")").hide();
});</script>

这是我的表格:

<form name="dropdown" size="1" id="portfolio-list">
<select name="portfolio-list" id="portfolio-list">
<option value="#" rel="all" class="current">All</option> 
<option value="#custom-exhibits" rel=custom-exhibits class=custom-exhibits>Custom Exhibits</option>
<option value="#permanent-installation" rel=permanent-installation class=permanent-installation>Permanent Installation</option>
</select>
</form>

任何帮助是极大的赞赏!

4

2 回答 2

0

让我们从您发布的代码中创建一个工作示例。

我注意到的第一件事是,表单和选择标签都具有相同的 id 属性( id 值在 HTML 文档中必须是唯一的),这就是"#portfolio-list"选择器无法按预期工作的原因,change事件是针对表单而不是针对选择标签(如果您不将数据发送回服务器,则不需要表单标签)。

此外,类似段落的选择器"#"+this.value以 # 开头,选项值也以 # 开头,最后选择器看起来像"##custom-exhibits,这不是有效的选择器。

在 jQuery 中,该.val()方法主要用于获取表单元素的值,.value是原生 JavaScript,虽然这两种方法都是正确的,但如果您使用的是 jQuery,那么最好使用他的方法。

<select name="portfolio-list" id="portfolio-list">
    <option value="all" rel="all" class="current">All</option> 
    <option value="custom-exhibits" rel="custom-exhibits" class="custom-exhibits">Custom Exhibits</option>
    <option value="permanent-installation" rel="permanent-installation" class="permanent-installation">Permanent Installation</option>
</select>

<p id="all" >paragraph1</p>
<p id="custom-exhibits" >paragraph2</p>
<p id="permanent-installation" >paragraph3</p>

<script>
jQuery(function ($) {
    $("#portfolio-list").on( 'change', function(e) {
        // get selected option value
        var val = $(this).val();
        // show element with that id
        $( '#'+val ).show();
        // hide all other elements
        $('p').not( '#'+val ).hide();
    });
});
</script>
于 2013-08-22T20:52:53.673 回答
0

The code you posted has nothing to do with 'anchors', which I assume refers to <a> tags.

Remember: jQuery selectors are based on CSS selectors. A leading . matches elements with that class, a leading # matches the element with that id.

The first line of the event handler will show the element whose id matches this.value. The second line will hide all <p> whose id does not match this.value. (BTW, jQuery provides a .not() function that is a bit easier to read)

An important bug: your options values all start with #, then the script concats # in front of it again. This is probably not what you want.

Side note: "As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers". Not that .bind() doesn't work, but .on() is shorter and more featureful.

于 2013-08-22T19:21:36.127 回答