如何保持对调用jquery插件的原始对象的引用?
我正在创建一个jquery插件,它在被调用的元素旁边添加一个帮助文本图标。如何获取对调用插件方法的原始输入/文本区域对象的引用 代码如下:如何保持对调用jquery插件的原始对象的引用?,jquery,jquery-plugins,Jquery,Jquery Plugins,我正在创建一个jquery插件,它在被调用的元素旁边添加一个帮助文本图标。如何获取对调用插件方法的原始输入/文本区域对象的引用 代码如下: <input text name="name" data-help-text="Enter your name here" class="helpon"> <input text name="age" data-help-text="Enter your age here" class="helpon"> <t
<input text name="name" data-help-text="Enter your name here" class="helpon">
<input text name="age" data-help-text="Enter your age here" class="helpon">
<textarea name="experience" data-help-text="Enter a short summary of your experience" class="helpon"> </textarea>
<script type="text/javascript">
$(document).on("ready", function() {
$.fn.showHelp = function() {
return this.each(function() {
self = $(this)
var icon = $('<icon class="icon-question" data-help-text="icon here">?</i>')
icon.on("click", function(){
//how do i get a reference to the input/textarea here on which this?
alert( self.data("help-text") )
});
self.after(icon);
});
};
$('.helpon').showHelp();
});
</script>
$(文档).on(“就绪”,函数(){
$.fn.showHelp=函数(){
返回此值。每个(函数(){
self=$(这个)
变量图标=$(“?”)
icon.on(“单击”,函数(){
//我如何在此处获取输入/文本区域的引用,该区域上有此文件?
警报(self.data(“帮助文本”))
});
self.after(图标);
});
};
$('.helpon').showHelp();
});
如何获取图标单击事件上输入/文本区域的引用?self引用的是objects数组中的最后一个对象(本例中为textarea)您可以使用事件对象获取目标元素
var icon = $('<icon class="icon-question" data-help-text="icon here">?</i>')
icon.on("click", function(){
// you can use the target of the event object
alert( $(e.target).data("help-text") )
});
var图标=$('?'))
icon.on(“单击”,函数(){
//您可以使用事件对象的目标
警报($(e.target).data(“帮助文本”))
});
您可以通过获取详细信息。您需要为
self
变量指定一个范围:
$.fn.showHelp = function() {
return this.each(function() {
var self = $(this)
var icon = $('<icon class="icon-question" data-help-text="icon here">?</i>')
icon.on("click", function(){
//how do i get a reference to the input/textarea here on which this?
alert( self.data("help-text") )
});
self.after(icon);
});
};
$('.helpon').showHelp()
$.fn.showHelp=函数(){
返回此值。每个(函数(){
var self=$(此)
变量图标=$(“?”)
icon.on(“单击”,函数(){
//我如何在此处获取输入/文本区域的引用,该区域上有此文件?
警报(self.data(“帮助文本”))
});
self.after(图标);
});
};
$('.helpon').showHelp()
我该怎么做?不确定你的答案提到了如何做?我只是在你的每个函数中用var
关键字声明了self
。这会将self的范围限制为每个循环