我有<span>
div 中的标签,当用户点击它们时会被删除。工作正常。
我想存储 .text()
在该 div 中的一个变量中。问题是未存储更新的 文本。
点击一个单词将其删除在此 jsFiddle .
如您所见,content
变量返回旧文本,而不是新修订的文本。
如何将更新后的文本存储到变量中?
jQuery:
jQuery(document).ready(function() {
jQuery(document).on("mousedown", ".hello span", function() {
// don't add full stop at the end of sentence if it already ends with
var endChars = [".", "?", "!"];
jQuery(this).fadeOut(function(){
var parentObj = jQuery(this).parent();
jQuery(this).remove();
var text = parentObj.find("span").first().html();
parentObj.find("span").first().html(ta_capitalizeFirstLetter(text));
text = parentObj.find("span").last().html();
if ( endChars.indexOf(text.slice(-1)) == -1 )
{
parentObj.find("span").last().html(text+".");
}
});
var content = jQuery(this).parent().parent().find('.hello').text();
alert(content);
});
});
最佳答案
获取新文本的代码应该移到 fadeOut
回调中。一旦动画完成并且元素被移除,父元素的 innerText 将被更新。这时应该从DOM中读取更新的内容。
// Cache the element
var $el = jQuery(this).parent().parent().find('.hello');
jQuery(this).fadeOut(function () {
jQuery(this).remove();
// Irrelevant code removed from here
...
var content = $el.text();
alert(content);
});
这是另一个简单的演示,代码最少,有助于更好地理解代码。
关于javascript - 通过 .text() 存储变量不是最新的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36867669/