2014-02-21 42 views
0

我有以下代码,使用html data attributes而不是jquery class name selectorsClassnames 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> 

参考

  1. docs.telerik.com - How To Use Kendo UI Declarative Initialization
  2. docs.telerik.com - MVVM/Declarative Initialization And HTML5 Data Attributes
  3. classnames for styling, data attributes for behavior
  4. Don't use class names to find HTML elements with JS
+1

在javascript中使用数据属性没有任何问题,所以我对这个问题有点困惑。但是,它们通常用于将数据与它们设置和访问的元素相关联以检索该数据,而不是仅使用元素进行选择。仅供参考,jQuery .data()方法也是检索或设置这些值的简单方法。 – kinakuta

回答

0

它的优良使用thouse属性,即使它们是HTML5的一部分 - 这就是他们的东西。特别是如果没有预期冲突。

如果你仍然想摆脱命名冲突,你可以使用命名空间与选择像

$('myns\\:[data-role='show-alert']') 
... 
<myns:button type="button" class='myButton' data-role='show-alert'> 

避免选择HTML5属性,这是不相关的代码。