开发者

Is there a += available for attr() and val()? [duplicate]

This question already has answers here: Is it possible to do ".value +=" in JQuery? (5 answers) Closed 8 years ago.

Since I've moved to jQuery development has sped up for a great deal, but there is one thing which has become a little more time-consuming: appending some string to an attribute/value.

For example, if you wanted 开发者_开发百科to append a letter to the value of a textbox, you would normally do:

input.value += 'a';

but now using jQuery, it has become:

input.val(input.val() + 'a');

I know it wouldn't be too hard to create a function which can do this and then append that function to jQuery.fn, but I was rather wondering whether there is such a function perhaps already available. I haven't found any so far. Or is there perhaps a better technique of appending a string to a value/attribute than what I'm doing at the moment?


If you know that your element has a value attribute, there is no reason not to use

input.value += 'a';

There is nothing to stop you using plain JavaScript in your jQuery scripts.

In fact,

input.val(input.val() + 'a');

has no benefits over using plain 'js', except if your input is a jQuery object and you want to chain methods.

I'd suggest overall

var $input = $('#someInput');
$input[0].value += 'a'; //get the DOM object from your jQuery object
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜