我正在创建一个jquery插件,在其被调用的元素旁边添加一个帮助文本图标。如何获取对调用插件方法的原始input / textarea对象的引用?
以下是代码:
<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>
如何在图标点击事件中获得对输入/ textarea的引用? self指的是对象数组中的最后一个对象(本例中是textarea)
答案 0 :(得分:1)
您需要为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()
答案 1 :(得分:0)
您可以使用事件对象来获取目标元素。
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") )
});
您可以通过here
获取详细信息