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