如何使用带有特殊字符的开关

时间:2016-08-04 17:25:23

标签: javascript jquery

假设我有这样的按钮:

<button>&divide;</button>

我想将switch操作符与字符串变量一起使用。

<!DOCTYPE html> 
<html lang="en">
<head>      
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>     
    <script type="text/javascript">

$(document).ready(function()
{  
  $("button").click(function(){
      var value=$(this).text();
      console.log(value);
    switch(value){

      case "÷":
         alert("OK");
         break;
      case "&divide;":
         alert("OK");
         break;
    }
  });   

}
);

    </script>   
</head>
<body>
<button>&divide;</button>
</body>
</html>

但是按钮click.console.log()中没有出现任何警报:

"÷"

我的浏览器 - firefox 39.0。

1 个答案:

答案 0 :(得分:1)

考虑 Html节点文本并不总是一个安全的真实来源......一个好的选择可能是放置一些属性,为您提供所需的信息并仅使用视图数据显示...

&#13;
&#13;
function CheckBtnTextCtrl($) {
  let 
    $btns = $('button')
  ;
  
  function smartTextSanitization(text) {
    let decoder = document.createElement('textarea');
    decoder.innerHTML = text;
    
    return decoder.value;
  }
  
  function onBtnClick(event) {
    let 
      $btn = $(this),
      $btnText = $btn.text(),
      text = smartTextSanitization($btnText)
    ;
    
    switch(text) {
      case "÷":      
        console.log('it is division');
        break;
    }
  }
  
  $btns.click(onBtnClick);
}

jQuery(document).ready(CheckBtnTextCtrl);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>&divide;</button>
&#13;
&#13;
&#13;

好方法(在我看来):

&#13;
&#13;
function CheckBtnCtrl($) {
  const ACTION_TYPES = {
    "SUM": 1,
    "DIVIDE": 2
  };
  
  let $btns = $('button');
  
  function onBtnClick(event) {
    let 
      $btn = $(this),
      action = $btn.data('actiontype')
    ;
    
    switch(action) {
      case ACTION_TYPES.SUM:
        console.log('ok, we need to sum values');
        break;
        
      case ACTION_TYPES.DIVIDE:
        console.log('ok, we need to divide values');
        break;
    }
  }
  
  $btns.click(onBtnClick);
}
jQuery(document).ready(CheckBtnCtrl);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-actiontype="2">&divide;</button>
&#13;
&#13;
&#13;