gpt4 book ai didi

javascript - 错误 - 在主页上添加文本计数器后(使用 Jquery 计算剩余字符) - 需要刷新页面

转载 作者:行者123 更新时间:2023-12-02 18:14:32 27 4
gpt4 key购买 nike

在完成 Railstutorial 练习(第 10 章)时,我使用 Jquery 来计算 Textarea 中的剩余字符数。它实际上有效但只有当我每次登录至少刷新一次页面时。这意味着每次登录后页面刷新一次并且完美运行后,查询才会执行。我已经使用 css 来实现 .countdown 方法。

所以,我的问题是..为什么需要我刷新页面才能查看页面上的剩余字符,还有是否有一些更好的方法。有人可以告诉我这里发生了什么吗?

CSS代码

 .countdown {
display: inline;
padding-left: 10px;
color: #338333;
}

这是 micropost.js.coffee 的代码

updateCountdown = -> 
remaining = 140 - jQuery("#micropost_content").val().length
jQuery(".countdown").text remaining + " characters remaining"


jQuery ->
updateCountdown()
$("#micropost_content").change updateCountdown
$("#micropost_content").keyup updateCountdown

这里是_micropost_form.html.erb的内容

<%= form_for(@micropost) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "Maximum characters: 140" %>

</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<span class="countdown"></span>
<% end %>

这是我登录并进入主页时的图像(不刷新页面)

view of Page without-refresh

这是我登录时的图像,转到主页并刷新页面

enter image description here

最佳答案

试试这个。

$(document).ready(function(){
var totalChars = 100; //Total characters allowed in textarea
var countTextBox = $('#counttextarea') // Textarea input box
var charsCountEl = $('#countchars'); // Remaining chars count will be displayed here

charsCountEl.text(totalChars); //initial value of countchars element
countTextBox.keyup(function() { //user releases a key on the keyboard
var thisChars = this.value.replace(/{.*}/g, '').length; //get chars count in textarea
if(thisChars > totalChars) //if we have more chars than it should be
{
var CharsToDel = (thisChars-totalChars); // total extra chars to delete
this.value = this.value.substring(0,this.value.length-CharsToDel); //remove excess chars from textarea
}else{
charsCountEl.text( totalChars - thisChars ); //count remaining chars
}
});
});

这是一个 fiddle http://jsfiddle.net/6C8zn/

关于javascript - 错误 - 在主页上添加文本计数器后(使用 Jquery 计算剩余字符) - 需要刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19419272/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com