0
我有以下代碼,使用html data attributes
而不是jquery class name selectors
如Classnames for styling, data attributes for behavior中的建議。此代碼工作正常。但是,它引用javascript文件中的html5數據屬性。如何改善此Javascript代碼中關注點的分離?
例
$("[data-role='show-alert']").click(function() {
//and
textValue = $("[data-role='employee-name-text']").val();
問題
什麼是避免HTML5數據的這種引用的JavaScript文件屬性的最佳方式? (通過使用模型或東西?)
注:我正在使用Kendo UI
框架。
頭
<head>
<title>HTML 5 Test</title>
<script type="text/javascript" src="lib/kendo/js/jquery.min.js"></script>
<script type="text/javascript" src="lib/kendo/js/kendo.web.min.js"></script>
<script type="text/javascript">
//CONTROLLER File
var textValue = '';
function getEmployeeBusinessFunction() {
var currentEmployeeName = textValue;
alert(currentEmployeeName);
}
</script>
<script type="text/javascript">
$(document).ready(function() {
$("[data-role='show-alert']").click(function() {
//textValue = $('.myPersonTextbox').val();
textValue = $("[data-role='employee-name-text']").val();
//Call Business Function
getEmployeeBusinessFunction();
});
});
</script>
</head>
身體
<body>
<form>
<input type="text" class='myPersonTextbox' name="personName" placeholder="Employee Name" data-role='employee-name-text' />
<button type="button" class='myButton' data-role='show-alert'>
Add</button>
</form>
</body>
參考
- docs.telerik.com - How To Use Kendo UI Declarative Initialization
- docs.telerik.com - MVVM/Declarative Initialization And HTML5 Data Attributes
- classnames for styling, data attributes for behavior
- Don't use class names to find HTML elements with JS
在javascript中使用數據屬性沒有任何問題,所以我對這個問題有點困惑。但是,它們通常用於將數據與它們設置和訪問的元素相關聯以檢索該數據,而不是僅使用元素進行選擇。僅供參考,jQuery .data()方法也是檢索或設置這些值的簡單方法。 – kinakuta