jquery .val() += idiom

放肆的年华 提交于 2019-11-30 01:48:59

问题


What's the clearest commonly used idiom for this jQuery snippet?

$('#someTextarea').val( $('#someTextarea').val() + someString );

It feels clunky to wrap the original code in a one-line function

EDIT: So I can pass a function, which is cool... but my real intentions are for jsfiddles, where I currently do stuff like this:

function lazylog (str) { 
    $('#ta').val( $('#ta').val() + str + '\n' );
}
// or
function lazylogPlain (str) {
    document.getElementById('ta').value += str + '\n';
}

// view results of little experiments
lazylog( test1() );
lazylog( test2() );
lazylog( test3() );
// etc...

Don't know if that context would produce different answers or just make me seem really lazy for wanting to type even less than that. console.log doesn't count, I want the textarea.


回答1:


Just don't use jQuery.

document.getElementById('someTextarea').value += someString;

will be clearer, faster, and works as well as the jQuery snippet. If you really want to use the $ selector, with only one element you can also

$('#someTextarea')[0].value += someString; // least to type

Other possibilities are the .val() method with a function

$('#someTextarea').val(function(index, oldValue) { return oldValue + someString; })

or a variant with .each() (which is [nearly] equivalent to what val() does internally for text inputs):

$('#someTextarea').each(function(){ this.value += someString; })

These both need a one-line function expression you didn't like, but they have the advantage of working for more than one selected elements (and not breaking for no matched element) and they also return the jQuery object to preserve the chainability feature.




回答2:


You can pass a function:

$(...).val(function(index, old) { return old + whatever; });



回答3:


I don't know about idiomatic but one way to simplify this jQuery expression is to use the overload of val which takes a function object as a parameter. jQuery will pass in the old value to the function and you pass back the new value.

$('#someTextarea').val(function(_, oldValue) { return oldValue + something; }); 



回答4:


$('#someTextarea').val(function() {
  return this.value + something;
});

or

$('#someTextarea').val(function() {
  return $(this).val() + something; 
});

or

// mentioned by SLaks, JaredPar

$('#someTextarea').val(function(i, oldVal) {
  return oldVal + something;
});


来源:https://stackoverflow.com/questions/10487850/jquery-val-idiom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!