gpt4 book ai didi

javascript - 更改页面加载时调用的事件绑定(bind)函数

转载 作者:行者123 更新时间:2023-12-03 10:32:02 25 4
gpt4 key购买 nike

我有一个select,并且我在其上绑定(bind)了change事件,因此一旦发生更改,我的函数就会触发。

事情是:当我的页面加载时,它会触发这个函数,这是我不希望发生的。我只希望它在用户实际更改下拉列表的值时触发。

我的选择下拉列表:

<select data-bind="options: Main.Items, 
optionsText: 'Name',
value: Main.SelectedItems,
optionsCaption: 'Please Select',
event: { change: function(data,event) { ItemClick(null) }}">
</select>

如果有人知道为什么它在加载时会触发,以及我如何解决这个问题,我将非常感激。

最佳答案

使用 knockout 时,这通常是一个危险信号。使用 computed observablessubscriptions在值变化时触发逻辑。例如:

var MainViewModel = function(){
var self = this;
self.Items = [{Name: 'apple'}, {Name: 'orange'}];
self.SelectedItems = ko.observable();

function ItemClick(newValue) {
alert(ko.toJSON(newValue));
}

self.SelectedItems.subscribe(ItemClick);
}

ko.applyBindings({ Main: new MainViewModel() });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<select data-bind="options: Main.Items,
optionsText: 'Name',
value: Main.SelectedItems,
optionsCaption: 'Please Select'"></select>

确保按上述方式设置 SelectedItems,或明确设置 undefined。也就是说,如果您使用 null 进行初始化,UI 将使用 optionsCaption 立即再次将其设置为 undefined,从而触发订阅。

PS。您的 View 建议可以选择多个项目(因为该属性是复数的),如果是这样,您需要 selecte 上的 multiple 属性以及 SelectedItemsthe selectedOptions binding 的 >observableArray .

PPS。您发布的代码的行为与实际代码的行为不同。也就是说,在下面的代码片段中,您可以看到绑定(bind) eventItemClick 函数只有在您第一次更改下拉列表时才会触发。

function ItemClick(x) {
alert(x);
}

var MainViewModel = function(){
var self = this;
self.Items = [{Name: 'apple'}, {Name: 'orange'}];
self.SelectedItems = ko.observable();
}

ko.applyBindings({ Main: new MainViewModel() });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<select data-bind="options: Main.Items,
optionsText: 'Name',
value: Main.SelectedItems,
optionsCaption: 'Please Select',
event: { change: function(data,event) { ItemClick(null) }}"></select>

关于javascript - 更改页面加载时调用的事件绑定(bind)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29165612/

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