jquery .val()+ = idiom [英] jquery .val() += idiom

查看:88
本文介绍了jquery .val()+ = idiom的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个jQuery片段最常用的成语是什么?

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

编辑:所以我可以传递一个很酷的函数...但我的真实意图是jsfiddles,我现在做的事情是这样的:

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...

不知道上下文是否会产生不同的答案或者只是让我看起来真的很懒,想要输入甚至更少。 console.log 不计算,我想要textarea。

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.

推荐答案

只是不要使用jQuery。

Just don't use jQuery.

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

将更清晰,更快速,并且与jQuery代码段一样有效。如果你真的想使用 $ 选择器,只有一个元素你也可以

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

其他可能性是 .val() 带函数的方法

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

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

.each() (这几乎相当于val()内部对文本输入的作用):

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

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

这两者都是需要一个你不喜欢的单行函数表达式,但它们具有为多个选定元素工作的优势(并且不会破坏没有匹配的元素),并且它们还返回jQuery对象以保留可链接性功能。

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.

这篇关于jquery .val()+ = idiom的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆