Javascript 如何使用jQuery选择上一个选项?
我有一个html页面,其中包含如下select元素:Javascript 如何使用jQuery选择上一个选项?,javascript,jquery,html,Javascript,Jquery,Html,我有一个html页面,其中包含如下select元素: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <select id="ExSele
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<select id="ExSelect">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
<br>
<br>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button onclick="ToTheNext()" id="btnext">Next</button>
</body>
</html>
function ToTheNext()
{
$('#ExSelect option:selected').next().prop('selected', true);
}
function ToThePrevious()
{
$('#ExSelect option:selected').prev().prop('selected', true);
}
我的问题是:如何使用Vanilla JavaScript或jQuery将所选项目更改为此标记的上一个选项
Jsbin示例:替换.attr'selected'、'selected';带有.prop'selected',true
下一个是上一个
并在按钮下添加jQuery脚本
常量select=$'ExSelect';
下一个功能
{
select.find'option:selected'。next.prop'selected',true;
}
函数prev
{
select.find'option:selected'。prev.prop'selected',true;
}
1.
2.
3.
4.
5.
6.
7.
8.
9
10
下一个
Prev两个问题-首先,使用attr,您将多个选项设置为selected,这可能不是您想要做的,因为它将阻止Prev按预期工作 按如下方式更改代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<select id="ExSelect">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
<br>
<br>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button onclick="ToTheNext()" id="btnext">Next</button>
</body>
</html>
function ToTheNext()
{
$('#ExSelect option:selected').next().prop('selected', true);
}
function ToThePrevious()
{
$('#ExSelect option:selected').prev().prop('selected', true);
}
如果您使用的是jQuery,那么请停止使用onclick属性,而是适当地分配单击处理程序
$('#btnext').on('click', function(){
$('#ExSelect option:selected').next().prop('selected', true);
});
$function{
$'btnext'。单击,函数{
$'ExSelect option:selected'。next.prop'selected',true;
};
$'btprev'。单击,函数{
$'ExSelect option:selected'.prev.prop'selected',true;
};
};
1.
2.
3.
4.
5.
6.
7.
8.
9
10
下一个
Prev使用$'ExSelect选项:selected'。Prev.prop'selected',true 只需使用prev而不是nextLike@ToniMichelCaubet说,只需使用prev而不是nextand.prop'selected',true而不是.attr'selected',selected';我现在觉得自己很笨……@Pv Viana我们去过:P你是说道具吗?不,prev找到第一场比赛的前一场,这意味着使用attr它不会起作用。我只在这个例子中使用了onclick属性。谢谢你的回答!