Javascript 如何更改隐藏值和
我目前正在尝试制作一个下拉菜单,从菜单中选择一个链接将更改隐藏值以及超链接的文本。这是基于Twitter的引导下拉列表,并使用jQuery:Javascript 如何更改隐藏值和,javascript,jquery,Javascript,Jquery,我目前正在尝试制作一个下拉菜单,从菜单中选择一个链接将更改隐藏值以及超链接的文本。这是基于Twitter的引导下拉列表,并使用jQuery: <div id="periodChooser" class="btn-group"> <input type="hidden" value="1" name="dtype" id="dtype1"></input> <a data-toggle="dropdown" href="javascript:;
<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>
不幸的是,虽然它没有返回任何特定的错误,但代码不起作用。有什么建议吗?将事件绑定到每一方
<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>
我认为这可以优化,并使其更可重用 首先,像$'.btn group'这样的jQuery选择器的使用效率很低 其次,如果您使用多个小部件,它将中断,因为上下文是整个文档,它将找到该class.btn组的所有元素 第三,使用绑定到父元素的单个事件处理程序比使用每个事件处理程序更有效 我在JSBin中提供了以下代码: 我在这里做了什么
<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>
当然,这里还需要做很多其他的事情,比如打开和关闭选项列表,滚动,可能还有很多其他的事情……没有任何变化-在从下拉列表中选择一个选项后,文本和值都应该改变。更新值看起来还可以,尽管您正在触发更改,你确定这对它没有任何影响?另外.find'.btn:eq0'不会选择任何内容,您的标记ps中没有任何带有.btn的元素。请检查下面的答案,没有必要使用循环。很好,我不得不修改它,使其最终只是.btn,而不是.btn:eq0,但现在一切都正常了。你知道为什么会这样吗?
<script>
$('.btn-group').each( /* Well, you know, the function goes here... */ );
</script>