jsFiddle:https://jsfiddle.net/x9bbb14n/
举个例子,我有以下HTML:
<select name="sweets">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option>Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div class="sweets"></div>
<select name="cars">
<option>Ford</option>
<option selected="selected">Jaguar</option>
</select>
<div class="cars"></div>
我有这个jQuery
$( "select" ).change(function () {
var str = "";
str = $( "select option:selected" ).text();
$( "div" ).text( str );
})
.change();
我知道这是不正确的但我希望能够选择一个选项并其 DIV进行更新,然后转到另一个菜单,选择一个选项并让它更新其< / em> DIV
我缺少任何明显的事情?
由于
答案 0 :(得分:2)
您可以使用当前单击的元素上下文以及下一个选择器来定位所需的div:
$( "select" ).change(function () {
var str = $(this).find("option:selected" ).text();
$(this).next().text( str );
}).change();
答案 1 :(得分:1)
使用 $(this)获取jquery中的当前对象
$("select").change(function () {
var str = $("option:selected", this).text();
$('.' + $(this).attr('name')).text(str);
}).change();
答案 2 :(得分:0)
$( "select" ).change(function () {
var selectname = $(this).attr('name');
var str = $(this).find("option:selected" ).text();
$( "div."+selectname ).text( str );
})
.change();
我发现这是最好的,因为DIV可以在页面上移动