jquery将中的值复制到其他区域

jquery replicate values in to other area

本文关键字:其他 区域 复制 jquery      更新时间:2023-09-26

是否有一种简单的方法可以将值复制到的其他区域

即,如果我有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事件。

您可以通过changebind函数在选择框上使用change事件,在事件处理程序中,您可以调用htmltext函数来设置相关div上的文本,通过val获取所选选项的值(您的option元素没有value属性,因此val将获取它们的文本)。在这两种情况下,您都可以通过传入第一个选择框的CSS选择器(例如$("#first"))的$(或jQuery)函数来查找元素。

您可以这样做,这样您就不必为每个选择/div:编写代码

$('select').change(function() {
    $('div[id^="' + this.id + '"]').text($(this).val());
});

JSFiddle示例

如果您使用绑定到视图/页面的JavaScript支持对象,您还可以查看knocket.js并实现MVVM(模型-视图-视图-模型)模式。