当使用javascript和alpine.js编程更改时,如何记录输入范围值



我创建了一个简单的应用程序,用于在输入范围更改时控制台记录输入范围值。当我用指针左右移动滑块时,它工作得很好,但当我使用javascript改变值时,滑块值确实改变了,但console.log不会启动,所以控制台没有日志。

// change input range value programmatically with javascript
const slider = document.getElementById('slider')
slider.value=4 // the input range button indicator has moved
// when change with mouse cursor manually the console.log successfully log the data value
// but when I do it programmatically with Javascript it fails to log the data
<div x-data="{data: 3}">
<input type="range" id="slider" name="slider" min="1" max="5" x-model="data" @change="console.log(data)">
</div>

以编程方式更改值不会触发更新。如果你调度一个事件,它将被捕获:

// Set bubbles to true so it can bubble up in the DOM
// Set cancelable to true so the event can be stopped (preventDefault)
let event = new Event('change', {bubbles: true, cancelable: true});
slider.dispatchEvent(event);

最新更新