如何从jQuery插件初始化中获取选择器字符串,以便使用事件委派。
这是一个简单的案例:
import ctypes
from ctypes.wintypes import *
import win32clipboard
from win32con import *
import sys
class BITMAPFILEHEADER(ctypes.Structure):
_pack_ = 1 # structure field byte alignment
_fields_ = [
('bfType', WORD), # file type ("BM")
('bfSize', DWORD), # file size in bytes
('bfReserved1', WORD), # must be zero
('bfReserved2', WORD), # must be zero
('bfOffBits', DWORD), # byte offset to the pixel array
]
SIZEOF_BITMAPFILEHEADER = ctypes.sizeof(BITMAPFILEHEADER)
class BITMAPINFOHEADER(ctypes.Structure):
_pack_ = 1 # structure field byte alignment
_fields_ = [
('biSize', DWORD),
('biWidth', LONG),
('biHeight', LONG),
('biPLanes', WORD),
('biBitCount', WORD),
('biCompression', DWORD),
('biSizeImage', DWORD),
('biXPelsPerMeter', LONG),
('biYPelsPerMeter', LONG),
('biClrUsed', DWORD),
('biClrImportant', DWORD)
]
SIZEOF_BITMAPINFOHEADER = ctypes.sizeof(BITMAPINFOHEADER)
win32clipboard.OpenClipboard()
try:
if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_DIB):
data = win32clipboard.GetClipboardData(win32clipboard.CF_DIB)
else:
print('clipboard does not contain an image in DIB format')
sys.exit(1)
finally:
win32clipboard.CloseClipboard()
bmih = BITMAPINFOHEADER()
ctypes.memmove(ctypes.pointer(bmih), data, SIZEOF_BITMAPINFOHEADER)
if bmih.biCompression != BI_BITFIELDS: # RGBA?
print('insupported compression type {}'.format(bmih.biCompression))
sys.exit(1)
bmfh = BITMAPFILEHEADER()
ctypes.memset(ctypes.pointer(bmfh), 0, SIZEOF_BITMAPFILEHEADER) # zero structure
bmfh.bfType = ord('B') | (ord('M') << 8)
bmfh.bfSize = SIZEOF_BITMAPFILEHEADER + len(data) # file size
SIZEOF_COLORTABLE = 0
bmfh.bfOffBits = SIZEOF_BITMAPFILEHEADER + SIZEOF_BITMAPINFOHEADER + SIZEOF_COLORTABLE
bmp_filename = 'clipboard.bmp'
with open(bmp_filename, 'wb') as bmp_file:
bmp_file.write(bmfh)
bmp_file.write(data)
print('file "{}" created from clipboard image'.format(bmp_filename))
上面的代码不起作用,因为.on选择器类型需要是字符串。所以问题是如何在插件初始化中获取选择器。
(function($){
$.fn.pluginTest = function(){
$(document).on("click", this, function(e){
// action here
});
}
}(jQuery));
如何以$(".box").pluginTest()
为例。我一直在搜索这个,有些人建议使用.selector,但现在它已被弃用和删除。
答案 0 :(得分:0)
您可以使用6
将事件处理程序添加到目标选择器。
JS CODE:
.selector
在上面的示例中,当您点击$(document).on("click",this.selector, function(e) {
alert('You clicked me!!!');
});
&amp;时,您将不会收到任何提醒您将仅在.bigBox
上获得警报,因为事件处理程序通过其选择器绑定到目标元素。
答案 1 :(得分:-1)
有数百页专门用于扩展jQuery。您没有解释为什么以下内容不适用于您的插件:
(function($){
$.fn.pluginTest = function(){
this.on("click", this, function(e){
// action here
});
return this;
}
}(jQuery));
例如:
(function($){
$.fn.pluginTest = function(){
this.on("click", this, function(e){
$(this).toggleClass('red');
});
return this;
}
}(jQuery));
$('.box').pluginTest();
.red { background-color: red; }
.box { cursor: pointer; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>