只要您的应用程序逻辑非常简单,前面的方法就可以了,请注意解决方案会弄乱您的视图模型的值,这些值可以是可观察的,并且它们可以具有与之关联的订阅或计算,因此通过更改值你改变你的视图模型。这是一个不同的解决方案,无需更新您的视图模型
ko.bindingHandlers.fakePlaceHolderWhenNeedIt = {
init: function (element, valueAccessor, allBindings, vm) {
if (!Modernizr.input.placeholder) {
var placeHolderVal = $(element).attr("placeholder");
if (placeHolderVal != null || placeHolderVal != '') {
var $element = $(element);
var value = valueAccessor()
var valueUnwrapped = ko.utils.unwrapObservable(value);
$element.keyup(function () {
var inputValue = $(this).val();
var $watermark = $(this).prev('.ie-placeholder');
if (inputValue == null || inputValue == '') {
$watermark.show();
}
else {
$watermark.hide();
}
});
var display = valueUnwrapped != null || valueUnwrapped != '' ? "block" : "none";
var left = $element.position().left;
var top = $element.position().top;
var paddingLeft = $element.css('padding-left');
var paddingRight = $element.css('padding-right');
var paddingTop = $element.css('padding-top');
var paddingBottom = $element.css('padding-bottom');
var height = $element.css('height');
var placeHolder = '<div class="ie-placeholder" style="position:absolute;left:' + left + ';top:' + top + ';padding-top: ' + paddingTop + ';padding-bottom: ' + paddingBottom + ';padding-left: ' + paddingLeft + ';padding-right: ' + paddingRight + ';height: ' + height + ';line-height:' + height + ';display:' + display + ';">' + placeHolderVal + '</div>';
$(placeHolder).click(function () { $element.focus(); }).insertBefore(element);
}
}
},
update: function (element, valueAccessor, allBindings, vm) {
if (!Modernizr.input.placeholder) {
var placeHolderVal = $(element).attr("placeholder");
if (placeHolderVal != null || placeHolderVal != '') {
var $element = $(element);
var value = valueAccessor()
var valueUnwrapped = ko.utils.unwrapObservable(value);
var $watermark = $element.prev('.ie-placeholder');
if (valueUnwrapped == null || valueUnwrapped == '') {
$watermark.show();
}
else {
$watermark.hide();
}
}
}
}