2012-10-24 34 views
0

的文本我目前正試圖創建一個下拉菜單,其中從菜單中選擇一個鏈接將更改隱藏值以及超鏈接的文本。這是基於Twitter的引導下拉列表,並使用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> 

不幸的是,雖然它不返回任何特定的錯誤,該代碼不起作用。有什麼建議麼?

+0

你能添加一個的jsfiddle? :) – Geert

+0

什麼是不工作? – billyonecan

+0

沒有任何變化 - 從下拉列表中選擇一個選項後,文本和數值都應該改變。 – Ollie

回答

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> 
+0

太好了,我不得不修改它,結果它只是'.btn'而不是'.btn:eq(0)',但現在所有的工作。任何想法,爲什麼這可能是? – Ollie

0

我認爲,這可以優化並使其更加可重複使用的。

首先,您使用的jQuery選擇器非常無效,如$('.btn-group')

其次它會打破,如果你將使用多個「小部件」,因爲上下文是整個文檔,它會找到所有具有該類.btn-group的元素。

第三,使用綁定到父元素<ul>而不是每個元素的單個事件處理函數會更有效。它被稱爲「事件代表團」。 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> 

當然,threre是必須要在這裏完成,如開啓和關閉「選項列表」,滾動和可能很多其他的事情很多其他的事情......