[英]How can I preserve first original value on keyup event in jQuery
Here is my fiddle: http://jsfiddle.net/dQ6vZ/22/ 这是我的小提琴: http : //jsfiddle.net/dQ6vZ/22/
I have a case where I have repeating elements with some numeric values. 我遇到的情况是重复带有一些数值的元素。
<div class="chars">
<textarea></textarea>
<span class="myVal">5</span>
<span class="pres"> - preserved: 5</span>
</div>
<div class="chars">
<textarea></textarea>
<span class="myVal">10</span>
<span class="pres"> - preserved: 10</span>
</div>
On keyup event (when typing text) I am supposed to preserve the very first original value from span element with class myVal but update the value in the same element as I type. 在keyup事件(键入文本时)时,应该保留myVal类中span元素的第一个原始值,但在与我键入的元素相同的值中更新值。
So if the original value was 5, I need to keep 5 while I replace the value visible to the user with a new value. 因此,如果原始值为5,则在用新值替换用户可见的值时,需要保留5。
My beginning looks something like this: 我的开始看起来像这样:
var new_value = 0;
$( ".chars" ).keyup(function() {
var preserved_increment = parseInt($(this).find(".myVal").text());
var text_length = parseInt($(this).find("textarea").val().length);
new_value = text_length + preserved_increment;
$(this).find(".myVal").text( new_value );
$(this).find(".pres").text( " - not preserved: " + preserved_increment );
});
Use the data function provided by jQuery for this task. 使用jQuery提供的数据功能来完成此任务。
I have updated your code to preserve the original value inside the text area. 我已经更新了您的代码,以保留文本区域内的原始值。 jsfiddle jsfiddle
To access the original value, simply call: 要访问原始值,只需调用:
var originalValue = $(this).find(".myVal").data("original")
use data-* attributes, and then use jQuery's .data
method to get the value 使用data- *属性,然后使用jQuery的.data
方法获取值
HTML 的HTML
<div class="chars">
<textarea></textarea>
<span class="myVal" data-preserved="5">5</span>
<span class="pres"> - preserved: 5</span>
</div>
JS JS
var preserved_increment = parseInt($(this).find(".myVal").data("preserved"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.