我有一个按钮和一个选项列表。这个想法是,当用户单击该按钮时,默认选项从禁用更改为最大值。和oposite -如果未选中输入,则默认设置再次禁用。但是该值返回未定义。如果我将第一个和最后一个更改为数值,一切都会正常工作。怎么了?
<input class="input" type="checkbox" value="1" name="select-pot[]">
<select id="select" name="q-count[]">
<option disabled selected> -- choose -- </option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
jQuery(function(){
jQuery(".input").click(function(){
var thefirst = jQuery(this).next('#select option:first').val();
var thelast = jQuery(this).next('#select option:last').val();
if( jQuery(this).is(':checked') )
jQuery(this).next('#select').val(thelast);
else
jQuery(this).next('#select').val(thefirst);
});
});发布于 2015-05-21 03:11:48
.next()获取下一个同级,因此您需要获取select并在之后使用.find()或.children():
var thefirst = jQuery(this).next('#select').find('option:first').val();
var thelast = jQuery(this).next('#select').find('option:last').val();发布于 2015-05-21 03:15:04
由于ID必须是唯一的,所以没有必要这样做:
jQuery(this).next('#select option:first')什么时候
jQuery('#select option:first')这样就足够了,再加上.next()会在这里失败,因为它会计算元素的兄弟元素,并对您传递的任何内容进行过滤,但您的过滤器会导致它不匹配任何内容。
取而代之的是:
jQuery(".input").click(function () {
var thefirst = jQuery('#select option:first').val();
var thelast = jQuery('#select option:last').val();
if (jQuery(this).is(':checked')) jQuery('#select').val(thelast);
else jQuery('#select').val(thefirst);
});发布于 2015-05-21 03:23:10
面向未来查看器的普通javascript替代方案
(function () {
"use strict";
var inputs = document.getElementsByClassName('input'), input;
for (var i = 0; input = inputs[i]; i++) {
input.addEventListener('click', function (e) {
e.target.nextElementSibling.lastElementChild.selected = e.target.checked;
e.target.nextElementSibling.firstElementChild.selected = !e.target.checked;
}, false);
}
})();<input class="input" type="checkbox" value="1" name="select-pot[]">
<select id="select" name="q-count[]">
<option disabled selected>-- choose --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
https://stackoverflow.com/questions/30358355
复制相似问题