在插件函数中调用 html 数据集
Call html dataset within a plugin function
<button class="draw-sector-button" data-sector_no="0">Draw first</button>
<section id="section-0"></section>
<button class="draw-sector-button" data-sector_no="1">Draw second</button>
<section id="section-1"></section>
一个 HTML 页面,有多个部分,每个部分都有按钮。
点击按钮触发插件,然后填充相关的section标签。问题是,在插件回调中获取标签数据集,但 "this" 指标不起作用:
$('.draw-sector-button').myDrawPlugin({ // my data table generator
param1 : 'foo',
param2 : 'bar',
onComplete : function(result) {
var i = $(this).data('sector_no'); // (i : undefined)
$('#section-'+i).html(result.data_table);
}
});
他们说的恰恰相反:
"you have access to the actual image node through the this keyword within the callback."
在 JQuery Learning Center 页面中。所以我很困惑。谁能提供解决方案?
能否请您分享 myDrawPlugin 定义以了解如何绑定和处理点击事件?
无论如何,this 在 onComplete 回调中将引用传递给插件函数的对象(参数),因此如果你想要按钮要访问的元素数据,那么当您在单击按钮时调用它时,您需要将相应的元素引用传递给 onComplete 回调。
看看这种处理方式是否适合你,
$.fn.myDrawPlugin = function(opts) {
// Button click handling
$(this).on("click", function(){
opts.onComplete(this, {data_table: "<div>Hello World!</div>"});
});
};
$('.draw-sector-button').myDrawPlugin({ // my data table generator
param1 : 'foo',
param2 : 'bar',
onComplete : function(element, result) {
var i = $(element).data('sector_no');
$('#section-'+i).html(result.data_table);
}
});
<button class="draw-sector-button" data-sector_no="0">Draw first</button>
<section id="section-0"></section>
<button class="draw-sector-button" data-sector_no="1">Draw second</button>
<section id="section-1"></section>
一个 HTML 页面,有多个部分,每个部分都有按钮。
点击按钮触发插件,然后填充相关的section标签。问题是,在插件回调中获取标签数据集,但 "this" 指标不起作用:
$('.draw-sector-button').myDrawPlugin({ // my data table generator
param1 : 'foo',
param2 : 'bar',
onComplete : function(result) {
var i = $(this).data('sector_no'); // (i : undefined)
$('#section-'+i).html(result.data_table);
}
});
他们说的恰恰相反: "you have access to the actual image node through the this keyword within the callback." 在 JQuery Learning Center 页面中。所以我很困惑。谁能提供解决方案?
能否请您分享 myDrawPlugin 定义以了解如何绑定和处理点击事件?
无论如何,this 在 onComplete 回调中将引用传递给插件函数的对象(参数),因此如果你想要按钮要访问的元素数据,那么当您在单击按钮时调用它时,您需要将相应的元素引用传递给 onComplete 回调。
看看这种处理方式是否适合你,
$.fn.myDrawPlugin = function(opts) {
// Button click handling
$(this).on("click", function(){
opts.onComplete(this, {data_table: "<div>Hello World!</div>"});
});
};
$('.draw-sector-button').myDrawPlugin({ // my data table generator
param1 : 'foo',
param2 : 'bar',
onComplete : function(element, result) {
var i = $(element).data('sector_no');
$('#section-'+i).html(result.data_table);
}
});