[英]Jquery Knockout - get element instance inside data-bind attribute
I have a select
element where i bind the css class using Jquery Knockout. 我有一个
select
元素,我使用Jquery Knockout绑定css类。
I want to access the current element instance directly from data-bind
attribute, without creating a property in the ViewModel
(because i have many select
elements which shares the same functionality) 我想直接从
data-bind
属性访问当前元素实例,而不在ViewModel
创建属性(因为我有许多共享相同功能的select
元素)
Is this possible? 这可能吗?
<select id="select1" data-bind="css: { 'no-value-selected': $item.val() == '' }">
<option value="">[Select a value]</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
EDIT Using ViewModel to achieve this (what i want to avoid) 编辑使用ViewModel实现这一点(我想避免的)
function ViewModel() {
this.select1HasNoValueSelected = ko.computed(function () {
return $("#select1").val() == '';
}, this);
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
<select id="select1" data-bind="css: { 'no-value-selected': select1HasNoValueSelected }">
You are on the wrong track with the css
binding because if you are not using observables it won't update your class if the value of your select is changes. 你使用
css
绑定的方法是错误的,因为如果你没有使用observable,如果select的值发生了变化,它就不会更新你的类。
However you can (miss)use the event
binding and subscribe on the change event: 但是,您可以(错过)使用
event
绑定并订阅更改事件:
<select id="select1" class="no-value-selected" data-bind="event: { 'change':
function() { $($element).val() == '' ?
$($element).addClass('no-value-selected') :
$($element).removeClass('no-value-selected') } }">
<option value="">[Select a value]</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
Demo JSFiddle. 演示JSFiddle。 (second drop-down)
(第二次下拉)
But the best solution is to not fight against KnockOut and have properties for each select on your view model: 但最好的解决方案是不与KnockOut作斗争,并为视图模型上的每个选择提供属性:
function ViewModel() {
this.select1Value = ko.observable()
};
<select id="select1" data-bind="css: { 'no-value-selected': !select1Value() },
value: select1Value">
<option value="">[Select a value]</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
Demo JSFiddle. 演示JSFiddle。 (third drop-down)
(第三次下拉)
Or don't use Kncokout for this function at all. 或者根本不使用Kncokout这个功能。
You can try to use $element
instead of $item
: 您可以尝试使用
$element
而不是$item
:
<select data-bind="css: { 'no-value-selected': $element.val() == '' }">
<option value="">[Select a value]</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
Docs: http://knockoutjs.com/documentation/binding-context.html 文档: http : //knockoutjs.com/documentation/binding-context.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.