自定义属性未定义

时间:2017-06-15 17:28:59

标签: javascript jquery

THIS内部jsFiddle我有2个按钮,每个按钮都有一个自定义数据方向属性:

function convertToPlain(rtf) {
    rtf = rtf.replace(/\\par[d]?/g, "");
    rtf = rtf.replace(/\{\*?\\[^{}]+}|[{}]|\\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]?/g, "")
    return rtf.replace(/\\'[0-9a-zA-Z]{2}/g, "").trim();
}

我试图在点击按钮时控制记录direction属性:

 <div class="btn-group" id="controls">
  <button type="button" class="btn btn-primary btn-sm" data-direction="left">Prev</button>
  <button type="button" class="btn btn-primary btn-sm" data-direction="right">Next</button>
</div>

但我得到的是var updateCounter = function(){ var direction = $(this).data("direction") if(direction === "left") { counter--; } else { counter++; } console.log(direction); } 。为什么呢?

1 个答案:

答案 0 :(得分:1)

更改 updateCounter 函数,使其只接受一个参数。

var numbers = [4, 9, 16, 25];
var counter = 0;
var updateCounter = function(ele){
  var direction = $(ele).data("direction")
  if(direction === "left") {
      counter--;
  } else {
      counter++;
  }
  console.log(counter);
  console.log(direction);
}

$('#numbers_wrapper').text(numbers[counter]);

$('#controls button').on('click', function(e){
  updateCounter(this);
  $('#numbers_wrapper').text(numbers[counter]);
});
.numbers {
    width: 34px;
    height: 34px;
    line-height: 34px;
    text-align: center;
    margin: 5px auto;
    border: 1px solid #286da9;
    background: #337ab7;
    color: #fff;
    border-radius: 2px;
}
.controls > div {
    display: inline-block;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<div class="container">
    <div class="numbers text-center" id="numbers_wrapper"></div>
    <div class="controls text-center">
        <div class="btn-group" id="controls">
            <button type="button" class="btn btn-primary btn-sm" data-direction="left">Prev</button>
            <button type="button" class="btn btn-primary btn-sm" data-direction="right">Next</button>
        </div>
    </div>
</div>