0
<script>
(function () {
  jQuery.fn.szThreeStateColor = function (settings) {
    var cfg = {
      "overBgColor": "green",
      "overFgColor": "white",
      "clickBgColor": "blue",
      "clickFgColor": "white"
    };
    if(settings) {
      $.extend(cfg, settings);
    }
    var clickIdx = -1;
    $thisObj = $(this);
    var iniBgColor = $thisObj.find("tbody td").css("background-color");
    var iniFgColor = $thisObj.find("tbody td").css("color");
    var iniHeight = $thisObj.find("tr").css("height");
    $thisObj.find("tbody tr").bind("mouseover", function (e) {
      if($(this).index() != clickIdx) {
        $(this).css({
          "background-color": cfg.overBgColor,
          "color": cfg.overFgColor
        });
      }
    });
    $thisObj.find("tbody tr").bind("mouseout", function (e) {
      if($(this).index() != clickIdx) {
        $(this).css({
          "background-color": iniBgColor,
          "color": iniFgColor
        });
      }
    });
    $thisObj.find("tbody tr").bind("click", function (e) {
      //console.log($(this).index() + ":" + clickIdx);
      if($(this).index() != clickIdx) {
        if(clickIdx >= 0) {
          $thisObj.find("tbody tr:eq(" + clickIdx + ")").css({
            "background-color": iniBgColor,
            "color": iniFgColor
          });
        }
        $(this).css({
          "background-color": cfg.clickBgColor,
          "color": cfg.clickFgColor
        });
        clickIdx = $(this).index();
      }
    });
    return this;
  }
})($);
$(document).ready(function () {
  $("#table1")
    .szThreeStateColor({
    "overBgColor": "#34ef2a",
    "overFgColor": "#000000",
    "clickBgColor": "#333333"
  });
  $("#table2").szThreeStateColor();
});
</script>
</HEAD>

<BODY>

<table id="table1" width='300' border='1'>
<thead>
<tr><td>name</td><td>city</td><td>age</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</tbody>
</table>



<table id="table2" width='300' border='1'>
<thead>
<tr><td>name</td><td>city</td><td>age</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</tbody>
</table>

このプラグインは、イベントが発生したときに異なるセルの色を設定mouseover, mouseout, clickします。プラグインは単一のテーブルでは正常に機能しますが、複数のテーブルが使用されると異常に機能します。たぶん、変数clickIdxは各テーブルで共有されています。その変数の共有を防ぐにはどうすればよいですか?

4

1 に答える 1

0

これを行うには、プラグインを でラップしますreturn this.each(function() {...})

jQuery.fn.szThreeStateColor = function (settings) {
   // ...
   return this.each(function() {
       // variables that need to be private go in here
   });
}
于 2013-03-10T07:52:47.903 に答える