如何解决在 jquery 插件中委托一个选择器
我正在为基于 jquery 的应用程序构建一个更简单的模态/覆盖插件。出现在已打开的叠加层内的叠加层触发器不起作用。可能是因为该插件将覆盖内容包装在另一个 div 中,从而弄乱了 DOM?
我尝试使用带有委托的点击(来自主体),但随后插件假定 <body>
是触发器元素,而不是使用实际的触发器元素。我对代表团有什么误解吗?
// The plugin core:
(function($) {
$.fn.overlay = function(action,options) {
this.on('click',function(e) { // <- #1: the event
console.log(this); // <- #2: "this" is the overlay trigger element in this case
var $overlay = $( $(this).data('overlay') ); // get the overlat ID in data-verlay=id
var content = $overlay.html(); // get the overlay HTML content
$overlay.html('<div class="class">'+content+'</div>'); // wrap the content in a DIV
// Other plugin logic
});
return this;
};
}( jQuery ));
// Then I initialize the plugin:
$(document).ready(function() {
$('[data-overlay]').overlay();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- And call it with: -->
<a data-overlay="#overlay_id">trigger</a>
<!-- While the overlay content is: -->
<div id="overlay_id">Overlay content being wrapper in a another div at runtime</div>
我尝试将上面的 #1 行写为:
$('body').on('click',this,function(e) { ... }
但这只是将 this
视为函数内的 <body>
所以控制台上方的 #2 行记录为正文标记而不是实际的触发器元素
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。