0

我目前正在尝试制作一个下拉菜单,从菜单中选择其中一个链接将更改隐藏值以及超链接的文本。这是基于 Twitter 的 Bootstrap 下拉菜单,并使用 jQuery:

<div id="periodChooser" class="btn-group">
   <input type="hidden" value="1" name="dtype" id="dtype1"></input>
   <a data-toggle="dropdown" href="javascript:;">Weekend</a>  
   <ul class="dropdown-menu">
      <li><a href="javascript:;" data-value="1">Weekend</a></li>
      <li><a href="javascript:;" data-value="2">Week</a></li>
      <li><a href="javascript:;" data-value="3">Midweek</a></li>
   </ul>
</div>

我尝试编写的脚本如下:

<script>
jQuery(function($){
    $('#periodChooser').each(function() {
        $('.dropdown-menu a').click(function() {
            $('.btn-group').find('input[type=hidden]').val($(this)
                    .data('value')).change();
            $('.btn-group').find('.btn:eq(0)').text($(this).text());
        });
    });         
});
</script>

不幸的是,虽然它没有返回任何特定错误,但代码不起作用。有什么建议么?

4

2 回答 2

1

将事件绑定到每个

<script>
       $('#periodChooser .dropdown-menu a').click(function() {
            $('.btn-group').find('input[type=hidden]').val($(this)
                    .data('value')).change();
             $('.btn-group').find('.btn:eq(0)').text($(this).text());
     });
</script>
于 2012-10-24T10:30:35.260 回答
0

我认为这可以优化并使其更可重用。

首先,您使用的 jQuery 选择器$('.btn-group')非常低效。

其次,如果您将使用多个“小部件”,它会中断,因为上下文是整个文档,它会找到该类的所有元素.btn-group

<ul>第三,使用绑定到父元素而不是每个元素的单个事件处理程序会更有效<a>。它被称为“事件委托”。http://api.jquery.com/delegate/

<script>
$('#periodChooser').each(function() {
    var $input = $('input', this),
        $select = $('>a', this);

    $('ul', this).on('click', 'a', function() {
        var $this = $(this);

        $input.val($this.data('value')).change();
        $select.html($this.html());
    });
});
</script>

我在 JSBin 中提供了这段代码:http: //jsbin.com/welcome/38724/edit

我在这里做了什么?

<script>
$('#periodChooser').each(function() {
    // Find and store input and "select" element only once.
    var $input = $('input', this),
        $select = $('>a', this); // This finds only direct child element <a>

    // Find the <ul> element inside the #periodChooser
    // Bind a click event that will "bubble up" from <a> elements that are children of it
    $('ul', this).on('click', 'a', function() {
        // Wrap a jQuery around the <a> element
        var $this = $(this);

        // Set the input value and execute "change" event(s)
        $input.val($this.data('value')).change();

        // Change the "select" title. Doesn't matter if you use html() or text() - choose yourself!
        $select.html($this.html());
    });
});
</script>

现在,您可以使用它在单个页面内制作多个小部件!:)

<script>
$('.btn-group').each( /* Well, you know, the function goes here... */ );
</script>

当然,这里还有很多其他事情要做,比如打开和关闭“选项列表”、滚动和可能还有很多其他事情......

于 2012-10-24T12:35:56.967 回答