如何在jquery中设置各个选项

问题描述 投票:0回答:1

我想为我的jquery插件代码设置单独的选项。但我无法单独设置。我试过“$ .each”功能。我使用jQuery和最新版本

$.fn.myMethods = function(option) {
  this.each(function() {
    const $item = $(this);
    $item.myMethods.option = $.extend({
      now: 1
    }, option);
  });
  return this;
}

$.fn.resultOfMyMethods = function() {
  this.each(function() {
    const $item = $(this);
    console.log($item.myMethods.option.now)
  });
  return this;
}

$('input').eq(0).myMethods({
  now: 123
});
$('input').eq(1).myMethods({
  now: 456
});

$('input').eq(0).resultOfMyMethods();
$('input').eq(1).resultOfMyMethods();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input/>
<input/>

预期成绩

123
456

实际结果

456
456
jquery plugins prototype settings option
1个回答
1
投票

您将属性分配给$.fn.myMethods对象,而不是实例。

您可以使用data()存储单个元素。

$.fn.myMethods = function(option) {

  const opts = $.extend({
    now: 1
  }, option);

  this.each(function() {
    const $item = $(this);
    $item.data('options', opts); // set on element
  });
  return this;
}

$.fn.resultOfMyMethods = function() {
  this.each(function() {
    const $item = $(this);
    console.log($item.data('options').now);// get from element
  });
  return this;
}

$('input').eq(0).myMethods({
  now: 123
});
$('input').eq(1).myMethods({
  now: 456
});

$('input').eq(0).resultOfMyMethods();// 123
$('input').eq(1).resultOfMyMethods();// 456
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input/>
<input/>
© www.soinside.com 2019 - 2024. All rights reserved.