我最近刚刚尝试了 Alpine.js,但我认为它太复杂或者我错过了理解它
这是我的代码:
<div x-data="wordcount()" class="wordcount-container">
<p x-text="wc"> </p>
</div>
<textarea id="writing" @keyup="wordcount().updateWordCount()" ></textarea>
let wordcount_writing = 0;
function wordcount(){
return {
wc: wordcount_writing,
updateWordCount(){
this.wc = document.getElementById("writing").value.length;
wordcount_writing = this.wc;
}
}
}
当我通过控制台日志在 textarea 上打字时,我尝试检查 wordcount_writing 变量,它工作正常,但 x-text 不行
最佳答案
使用 Alpine.js 的数据模型,您无需执行任何操作即可获取文本长度。您可以定义模型数据writing
,将其绑定(bind)到textarea
x-model
,然后你可以通过writing.length访问它的长度。该变量是 react 性的,因此您不必手动更新长度。
<script defer src="https://cdn.jsdelivr.net/npm/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="640508140d0a010e1724574a1c4a1c" rel="noreferrer noopener nofollow">[email protected]</a>/dist/cdn.min.js"></script>
<div x-data="{ writing: '' }">
<p x-text="`Text length: ${writing.length}`"></p>
<textarea x-model="writing"></textarea>
</div>
关于javascript - 变量更新时 x-text 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76145379/