是否有一种简单的方法可以引用调用.val()或.text()的元素值而无需双重选择或缓存?
例如:
//NO
$(this).val($(this).val() + 'something');
//NO
var $this;
$this.val($this.val() + 'something');
Run Code Online (Sandbox Code Playgroud)
相反,在.replace()中使用诸如$&token之类的东西
'some string'.replace('str', '$&123');
//results - 'some str123ing'
Run Code Online (Sandbox Code Playgroud)
谢谢.
您可以将函数传递给.val(),如下所示:
$(this).val(function(i, currentVal) { return currentVal + 'something'; });
//another example:
$(this).val(function(i, cVal) { return cVal.replace('str', '$&123'); });
Run Code Online (Sandbox Code Playgroud)
这适用于任意数量的元素,函数i是索引,currentVal是什么$(this).val()可以得到你.只需在该函数中返回您想要的新值即可.
| 归档时间: |
|
| 查看次数: |
323 次 |
| 最近记录: |