[英]Dynamically change an input field's placeholder?
我正在使用 Javascript 和 d3 庫以及 AngularJS。
有沒有辦法動態更改輸入框的占位符? 我正在使用日歷小部件和多個視圖,想看看是否有辦法讓占位符始終是最后輸入到字段中的值。
我寫了一個小函數,它總是返回輸入字段的最后一個東西……但是當我嘗試設置 placeholder=functionIwrote() 時,它實際上使占位符“fucntionIwrote()”而不是運行該函數。
我無法發表評論,但是...如果您使用 angularJs,您只需將輸入模型綁定到占位符即可!
<input type="date" placeholder="myModel" ng-model="myModel" />
這樣,您的輸入將始終是最新的填充值。
如果你想改變你的視圖,然后檢索數據,那么你必須將它們存儲在控制器范圍之外——如果你使用 ngIf 指令,每次都會“清理”它。
這樣做的一個好方法是使用服務作為持久層。
由於您希望automatically
和dynamically
更改或更新placeholder
,您可以使用下面的 jQuery 代碼:
$(function() {
$('input').on('change blur', function() {
!this.value || $(this).attr('placeholder', this.value);
});
});
是的,你可以這樣做,
<input
placeholder="Select Date"
onfocus="(this.type='date')"
onblur="if (!this.value) this.type = 'text'">
這是一個小提琴: http : //jsfiddle.net/bBh3L/
'placeholder' 是一個元素屬性,所以你可以使用 $('#myInput').attr(attributeName, attributeValue) 來設置它。
在這種情況下,我映射了按鈕單擊以使用以下方法更改占位符:
$('#myInput').attr('placeholder', 'new one');
我猜你正試圖將你的日歷小部件包裝成一個角度指令,如果是這樣,這是我為類似用例所做的(我將接受/有效格式顯示為占位符):
module.directive('yourDirective', [function() {
return {
link: function($scope, $element, $attrs, $controller) {
// bind 'yourValue' (the one you want to show as placeholder) in the scope
$scope.$watch('yourValue', function(value) {
$attrs.$set('placeholder', value);
});
}
};
}]);
AngularJS ng-attr-{property_name}
存在一個條件屬性屬性
例如,我使用不同的占位符用於不同的搜索選項
ng-attr-placeholder="{{isAdvanceSearch ? setPlaceholder(searchOption) : 'John Smith, 08/23/1970, 123'}}"
這里基於isAdvanceSearch
變量,我在setPlaceholder
方法中設置了不同的占位符。
setPlaceholder
方法返回要在輸入字段中設置的占位符。
$scope.setPlaceholder = function(searchOption) {
if (searchOption === "foo") {
return "Search by foo… e.g. foo1";
} else if (searchOption === "bar") {
return "Search by bar… e.g. bar123";
} else {
return "John Smith, 08/23/1970, 123";
}
};
注意: John Smith, 08/23/1970, 123
是默認占位符。 不要忘記將表達式括在{{}}
方括號中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.