You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Alpine.js中x-on:click指令无法识别this属性的原因咨询

Alpine.js指令中为何无法使用this属性?

下面这段代码可以正常运行:

<input
id="chk-products"
name="chk-products"
type="checkbox"
x-on:click="showProducts = document.getElementById('chk-products').checked">

但改用this.checked的代码却无法运行:

<input
id="chk-products"
name="chk-products"
type="checkbox"
x-on:click="showProducts = this.checked">

原因很明确:Alpine.js的指令表达式运行在组件的上下文作用域中,而非DOM元素的作用域。这里的this指向的是Alpine组件的实例(即x-data定义的数据对象),不是触发点击事件的复选框元素本身,所以无法获取到checked属性。

如果要访问触发事件的DOM元素,Alpine提供了专门的$event变量,通过$event.target就能获取当前元素,修正后的代码如下:

<input
id="chk-products"
name="chk-products"
type="checkbox"
x-on:click="showProducts = $event.target.checked">

另外,你也可以用x-model简化逻辑,Alpine会自动同步复选框状态到目标变量:

<input
id="chk-products"
name="chk-products"
type="checkbox"
x-model="showProducts">

内容的提问来源于stack exchange,提问作者PlanBuildr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:01:20