简体   繁体   English

如何用jQuery“附加”一个值而不是完全替换它?

[英]How to “append” a value with jQuery instead of replace it completely?

The way I understand val works is that when you do 我了解val的方式是

$(".foo").val("x") 

you literally replace the value for the input. 您可以从字面上替换输入的值。 Does anything in jQuery 2.x support a "append" like function instead? jQuery 2.x中的任何东西都支持类似功能的“追加”吗? I found a unit/integration like scenario that would let me reproduce a real but ... except that val replaces the input's value completely instead of "just adding a single char" like my end user would. 我发现了一个类似于单元/集成的方案,该方案可以让我重现一个真实的...但是除了val完全替换输入的值,而不是像最终用户那样“仅添加单个字符”。

Access the callback function of .val( cb ) and return the current value concatenated with a string of your choice: 访问.val( cb )的回调函数,并返回与您选择的字符串连接的当前值:

 $(".foo").val(function(i, currVal) { return currVal + "whatever"; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="foo" tyle="text" value="A-"> <!-- A-whatever --> <input class="foo" tyle="text" value="B-"> <!-- B-whatever --> 

If you want a jQuery method like .valAppend() than you can create one: 如果您想要像.valAppend()这样的jQuery方法 ,则可以创建一个:

$.fn.valAppend = function( str ) {
  return this.val( this[0].value + str );
};

// Use like:
$(".foo").valAppend( "whatever" );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM