【发布时间】:2018-12-23 10:38:13
【问题描述】:
我正在尝试为我的网页创建一个简单的 jquery 插件,这里面临的问题是即使对于动态内容也能处理点击。
我尝试过使用document on click selector,但它不起作用,但是在页面加载时使用select on click 可以正常工作,但在动态内容上却不行。当我使用$(document).on("click", clickedElement, function(event) 进行单击事件时,安慰$(this).data("object-id") 将显示未定义。
<span class="openModalTemplate" data-object-id="item100">Open 1</span>
<span class="openModalTemplate" data-object-id="item101">Open 2</span>
<span class="openModalTemplate" data-object-id="item103">Open 3</span>
<script>
$(function(){
$(".openModalTemplate").Template({
element: "#newOpen"
type: "product"
});
});
</script>
我的功能
(function($){
$.fn.Template = function(options) {
var clickedElement = $(this);
if(typeof options === "object") {
options = $.extend(true, options, {
/*Locals*/
element: '#createObjectElement',
type: "product",
action: null,
apiURL: null,
object: null,
categoryType: "ITEM"
});
}
$(document).on("click", clickedElement, function(event){
//clickedElement.on("click", function(event){
var currentElemnt = $(this);
var action_id = $(this).data("object-id");
//if(action_id === undefined){action_id = options.action;}
if(options.type =="close"){
}
console.log("action_id", action_id);
console.log("element", options.element);
if (options.onAfterOpen !== undefined) {
options.onAfterOpen(event);
}
if (options.onAfterClose !== undefined) {
options.onAfterClose(event);
}
if (options.onError !== undefined) {
options.onError(event);
}
event.preventDefault();
});
};
})(jQuery);
【问题讨论】:
-
不幸的是从搜索插件内部无法做到这一点..为当前元素而不是新元素设置的插件..所以你需要运行再次为新创建的元素插件..你可以看看Here
-
是的,这是个好主意,而且奏效了
-
@Mohamed-Yousef 问题是有时它会多次执行 pligin 函数
-
正如我所说,彼得 再次为 新元素 运行插件 .. 为新元素添加一个新类并为此运行插件类
-
我用解决方案更新了我的答案..检查它
标签: javascript jquery jquery-plugins