2014-02-21 45 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屬性,這是不相關的代碼。