jQuery ui resizable 将resize事件的变量传给stop事件

jQuery ui resizable Pass variables of resize event to stop event

我需要传递调整大小事件的变量“blabla”来停止事件我该怎么做?

在此先感谢部分代码来解释我需要什么:

.resizable({
                        disabled: disablePoignee,
                        handles: poignees,
                        resize: function (e, ui) {
                            var blabla = "pioup";
                        },
                        stop:function(e,ui){
                            //try to get blabla
                        }});

预先感谢您的帮助

在此代码中...

.resizable({
  disabled: disablePoignee,
  handles: poignees,
  resize: function (e, ui) {
    var blabla = "pioup";
  },
  stop: function(e,ui) {
    //try to get blabla
  }});

... 变量 blabla 仅在传递给 resizable 插件函数的函数内部可用(作为 options 对象的 resize 属性)。这个值是封装的 - 本质上是隐藏的 - 来自世界其他地方。

要'unhide'呢,你有两个选择。首先,使这个变量在 resizestop 函数的范围之外:

var blabla; // or const, or let
// ...
.resizable({
  resize: function (e, ui) {
    blabla = "pioup"; // note that `var` shouldn't be used here, as existing variable is reused
  },
  stop: function(e, ui) {
    doSomethingWith(blabla);
  }});

但是,如果在您的代码中创建了多个 resizable 实例,并且每个实例都应使用其自己的 blabla 值,则该方法将不起作用。在这种情况下,使用第二个选项可能会有用 - 并将一些自定义 属性 分配给托管插件的 jQuery 对象:

.resizable({
  resize: function (e, ui) {
    ui.originalElement.data('blabla', 'someValue'); 
  },
  stop: function(e, ui) {
    doSomethingWith(ui.originalElement.data('blabla')); 
  }});

这种方法的好处是即使插件被销毁,数据仍然附加到这个对象。

考虑以下示例。

$(function() {
  $("#resizable").resizable({
    resize: function(e, ui) {
      $(this).data("foo", "bar-" + $(this).width());
    },
    stop: function(e, ui) {
      console.log($(this).data("foo"));
    }
  });
});
#resizable {
  width: 150px;
  height: 150px;
  padding: 0.5em;
}

#resizable h3 {
  text-align: center;
  margin: 0;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="resizable" class="ui-widget-content">
  <h3 class="ui-widget-header">Resizable</h3>
</div>

您可以使用 jQuery Data.

而不是创建更全局的变量

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

有了这个,我们可以为每个元素设置和获取数据。如果您只有一个可调整大小的元素,这没什么大不了的。如果您有很多可调整大小的项目,这对合并您的脚本非常有帮助。