类似于此:Event binding on dynamically created elements?
但我不是动态地添加元素,而是使用.addClass将类动态地添加到元素中。
基本html:
<div id="WebPartWPQ6_ChromeTitle">
<a accesskey="W" href="/siteurl" >
<span>Access </span></a></div>功能:
(function($){
$.fn.sharePop = function(){
if(typeof OpenPopUpPage == 'function'){
return this.each(function(i){
if($(this).attr('href') != null){
$(this).click(function(e){
e.preventDefault();
OpenPopUpPage($(this).attr('href'));
});
}
});
}
else{
return false;
}
};
})(jQuery);
$(document).ready(function(){
$('.dialog-pop').sharePop();
});添加类:
$( document ).ready(function() {
$( "#WebPartWPQ6_ChromeTitle a" ).addClass( "dialog-pop" );
});这门课加得很好。但我的假设是,当事件连接到元素时,它并不存在--这一行需要改变:
$(this).click(function(e){我试过这个:
$(this).on('click', '.dialog-pop', function(e){但没有运气。
发布于 2017-12-10 22:00:17
$(document).on('click',‘.对话框-pop’,函数(){返回函数{代码在这里};});
发布于 2017-12-10 22:39:56
基本上,当您实例化元素时
$('.dialog-pop').sharePop()它使用.dialog-pop在document中搜索元素,并按您所写的绑定事件。因此,如果有一个新的动态添加的元素,无论元素是否有首先实例化的选择器,sharePop函数都不知道该做什么。因此,与其添加类,不如直接实例化元素。
$('#WebPartWPQ6_ChromeTitle a').sharePop()如果您需要使用所选的选择器,则事件委托是可行的。如果强制不能确定要使用的选择器,并且目前使用的是jQuery 1.7或更低版本,则.selector属性可能会有所帮助。
哦,有一点要注意的是,我认为销毁以前相同的事件--防止它执行两次,等等-- (尽管您使用preventDefault)是好的。
$.fn.sharePop = function() {
if (typeof OpenPopUpPage == 'function'){
var selector = this.selector
$(document).off('click').on('click', selector, function (e) {
e.preventDefault()
var href = $(this.attr('href'))
if (href) {
OpenPopUpPage($(this).attr('href'))
}
})
return this
}
return false
};或者,如果您的版本jQuery大于1.7,则将选择器作为参数应用。还请注意,我使用命名空间事件来防止破坏其他已经附加的click事件。
$.fn.sharePop = function(selector) {
if (typeof OpenPopUpPage == 'function'){
if (typeof selector === 'string') {
$(document).off('click.openpopup').on('click.openpopup', selector, function (e) {
e.preventDefault()
var href = $(this.attr('href'))
if (href) {
OpenPopUpPage($(this).attr('href'))
}
})
} else {
// attach the event like you already did?
}
return this
}
return false
};实际上,如果我不像$.fn.sharePop那样共享$('.dialog-pop').sharePop('refresh')或$('.dialog-pop').sharePop('destroy')之类的方法/API,而不是直接将事件绑定到文档上,那么我就永远不会创建这样的插件。
https://stackoverflow.com/questions/47743890
复制相似问题