简体   繁体   English

我如何使用jQuery将某些内容附加到表单元素的值,而不是更改它?

[英]How can I use jQuery to append something to the value of a form element, as opposed to changing it?

I know how to do this in basic JS: 我知道如何在基本的JS中做到这一点:

document.getElementById("someTextarea").value += "stuff";

Note the + - I'm adding to the value, not completely changing it. 注意+ - 我正在添加值,而不是完全改变它。 How would I do that using jQuery's val() ? 我如何使用jQuery的val()来做到这一点?

$('#foo').val($('#foo').val() + 'something');

(Of course you can and should cache the element). (当然你可以而且应该缓存元素)。

Another way (very jQuery style): 另一种方式(非常jQuery风格):

$('#foo').val(function(){
    return this.value + "something";
});
$('#someTextarea').val(function(i, v){ return v + 'stuff'; });

Since an ID selector will return a unique element you can avoid val if you want: 由于ID选择器将返回一个唯一元素,因此您可以根据需要避免使用val

$('#foo')[0].value += ' stuff'; $('#foo')[0] .value + ='stuff';

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

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