[英]Setting HTML property with JQuery
我正在結合使用JQuery,Modernizr和Angular為通過ng-repeat生成的表實現自定義Datepicker解決方案。 如果將“ datepicker”的Angular指令硬編碼到HTML中,則該解決方案有效 。
因此,例如,在我的表格中使用ng-repeat"revenue in runway.revenues"
可以正常工作:
<td>
<input type="date" class="form-control" ng-model="revenue.date" placeholder="YYYY-MM-DD" datepicker required/>
</td>
但是我希望僅在用戶使用瀏覽器時才需要這樣做。 因此,考慮到這一點,我從上面的HTML中刪除了datepicker
,並用JS編寫了它:
$(function() {
var nativeDateInputIsSupported = Modernizr.inputtypes.date;
if (!nativeDateInputIsSupported) {
$('input[type="date"]').prop("datepicker", true)
}
});
但是,當我進入Firefox的頁面時,它似乎無法正常工作。
此外,如果我嘗試通過類似console.log($('input[type="date"]').prop("class"))
進行調試,則返回的值將是undefined
(應為form-control
) 。
任何提示將非常感謝!
使用.attr()
或.setAttribute()
在HTML上設置屬性
document.querySelector("input").setAttribute("datepicker", true); console.log(document.querySelector("input").outerHTML);
<input type="text">
$("input").attr("datepicker", true); console.log($("input")[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <input type="text">
$("input").prop("datepicker", true); console.log($("input")[0].outerHTML); // attribute not set at HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <input type="text">
通過從用戶@ guest271314獲得一個想法並對其進行擴展,我能夠使其工作!
我沒有將屬性添加到基於Modernizr的HTML中,而是將$ scope變量設置為一個布爾值。
$(function() {
var nativeDateInputIsSupported = Modernizr.inputtypes.date;
if (!nativeDateInputIsSupported) {
$scope.datePickerValue = "true"
}
});
在我的指令中,我添加了以下內容:
function link(scope, element, attrs, controller) {
var requiredParam = attrs.datepicker === 'true'; //This was what was added
if (requiredParam) { //Checking for boolean value
element.datepicker({
dateFormat: "yy-mm-dd",
maxDate: '0'
});
}
}
這意味着我在HTML datepicker="{{datePickerValue}}"
到Date輸入中,現在可以使用了! 謝謝您提供的所有幫助,如果沒有您的投入,我將不會再回到這個問題上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.