jquery将中的值复制到其他区域
jquery replicate values in to other area
是否有一种简单的方法可以将值复制到的其他区域
即,如果我有2个或3个选择菜单或其他表单字段。
比如
<select id=first>
<option>1</option>
<option>2</option>
</select>
<select id=second>
<option>3</option>
<option>4</option>
</select>
<div id=firstvalue></div>
<div id=secondvalue></div>
如果我想让divs.html自动显示选择框的值,我是否必须对任何一个组件执行一段更改代码?
感谢
Lee
您想要一个代码同时处理两个代码吗?试试这个(jsFiddle上的例子)
$("select").change(function() // retrieve all `select` elements
{
// gets the corresponding `div`
$("div").eq($(this).index())
.html($(this).val()); // sets the html value of the `div` to
// the selected value on the `select` element
});
来自jQuery文档:
- 选择器
- .change()
- .eq()
- .index()
- .val()
如果您想让div自动显示任何选择框的选定值,您可以使用以下jQuery:
$('#first').change(function(){
/* target the first selectbox with id #first and bind a change event to it */
$('#firstvalue').html($(this).val());
/* set the html of the div with id #firstvalue to the selected option*/
});
/* the same for the second selectbox */
$('#second').change(function(){
$('#secondvalue').html($(this).val());
});
不过,我建议您更改HTML,以便正在处理的选择框具有相同的类,并将其目标存储在data
属性中。像这样:
HTML
<select class="show_val" data-target="#value_1">
<option>1</option>
<option>2</option>
</select>
<div id="value_1"></div>
jQuery
$('.show_val').change(function(){
$($(this).data('target')).html($(this).val());
}
通过这种方式,您可以对所有选择框使用相同的jQuery事件。
您可以通过change
或bind
函数在选择框上使用change
事件,在事件处理程序中,您可以调用html
或text
函数来设置相关div上的文本,通过val
获取所选选项的值(您的option
元素没有value
属性,因此val
将获取它们的文本)。在这两种情况下,您都可以通过传入第一个选择框的CSS选择器(例如$("#first")
)的$
(或jQuery
)函数来查找元素。
您可以这样做,这样您就不必为每个选择/div:编写代码
$('select').change(function() {
$('div[id^="' + this.id + '"]').text($(this).val());
});
JSFiddle示例
如果您使用绑定到视图/页面的JavaScript支持对象,您还可以查看knocket.js并实现MVVM(模型-视图-视图-模型)模式。
相关文章:
- onkeyup无法动态创建多个文本区域
- 如何添加浮动和非浮动,其他
- 与其他库的jQuery.noConflict()
- 播放当前视频时如何停止其他视频?JavaScript
- FabricJs-限制主对象内添加对象的移动区域
- 清除文本区域会中断其他JS函数
- 如何将用户输入传递到其他文本区域
- j查询验证模糊文本区域与其他输入问题
- 将文本插入到其他页面上的文本区域中
- 使用 geojson 确定给定地理位置与哪些其他地理区域共享边界
- AngularJS-动态创建<text区域>使用ngSanitize不会't显示(其他元素显示)
- 从一个文本区域复制到所有其他文本区域
- 将文本区域中的字符串替换为其他文本
- 当改变一个文本区域的值改变其他值
- Javascript "if else"当条件不满足时,不会进入其他区域
- 如何在某些区域用JS捕获键盘箭头,而不是其他区域
- 当选择“其他”选项时显示文本区域
- jquery将中的值复制到其他区域
- 在其他数据标签上带有数据标签的Highcharts区域
- 当悬停其他内容时,下拉/在一个区域显示特定内容