当下拉菜单中的项目发生变化时,以简洁的方式突出显示标签
Concise way to highlight label when items in dropdown changes?
我想在相关的下拉值发生变化时用颜色突出显示标签。
<tr>
<td>
<select id="first_dd" data-bind="value: first">
<option>cat</option>
<option>dog</option>
<option>squirrel</option>
<option>birds</option>
</select>
</td>
<td>
<label id="first_lb">
soft</label>
</td>
</tr>
<tr>
<td>
<select id="second_dd" data-bind="value: second">
<option>lion</option>
<option>elephant</option>
<option>kangaroo</option>
<option>buffalo</option>
</select>
</td>
<td>
<label id="second_lb">
dangerous</label>
</td>
</tr>
当用户更改first_dd
项时,我想更改first_lb
的颜色。
我如何用更少的代码在JavaScript/jQuery中完成这一点?
所以,这里是"less code"。为select
添加更改事件处理程序
试试这个:
$("#first_dd").change(function(){
$("#first_lb").css('color',"yellow");
});
编辑:
因为你的问题只要求first_dd
和first_lb
,所以我只为那部分添加了代码。要将此应用于所有select
使用jquery .each()
.
如果你动态添加元素,那么你必须使用on
来绑定events
,否则使用.change()
就足够了。
所以正如你提到的你的要求,这样做:
$('select').each(function(){ //for each select elements in document
$(this).on('change',function(){ //bind change event
var id = $(this).attr('id').replace('dd','lb'); //get id for label
$("#"+id).css("color","yellow"); //highlight
})
})
使用for属性来连接标签和相关的select dom元素,如
<select id="first_dd" data-bind="value: first">
<option>cat</option>
<option>dog</option>
<option>squirrel</option>
<option>birds</option>
</select>
<label for="first_dd">soft</label>
添加JS来检测更改并添加类
$('select').each(function(){
$(this).on('change',function(){
$('label[for="'+$(this).attr('id')+'"]').addClass('changed')
})
})
和添加适当的CSS改变类
.changed {
color: #000;
}
相关文章:
- 为什么这在IE中的工作方式与在Firefox中不同
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- 在localhost Dev Box上测试JSONP请求的最佳方式
- 使用javascript存储变量的最安全方式
- 以可优化的方式使用requirejs加载模板
- 在Highcharts中,我们可以通过任何方式在渲染图表之前获得plotWidth和plotHeight
- 任何方式使AJAX调用Gmail API,而无需通过JS库
- 为react组件传递道具的最佳方式
- 让Webpack管理Quirky AMD定义的最佳方式
- 链接承诺和传递价值的简洁方式
- JavaScript if语句的简洁方式
- 运行多事件功能的更简洁的方式
- 当下拉菜单中的项目发生变化时,以简洁的方式突出显示标签
- 写一个coffeescript函数,将json数组转换成我想要的格式,这是一种简洁的方式
- 以更简洁的方式声明javascript静态方法
- 简洁的方式获取所有输入字段的值
- 将事件附加到动态呈现字段的更简洁的方式
- 使用JQuery和Angular2进行多个ajax调用的简洁方式
- 定义Angular模板的更简洁的方式