Javascript 在jQuery插件中访问原始目标元素

Javascript 在jQuery插件中访问原始目标元素,javascript,jquery,Javascript,Jquery,我组装了一个jQuery插件来查询服务器并显示工具提示弹出窗口。是的,我知道可能有更好的,但我一半的动机是自己学习如何这样做。现场演示位于,脚本如下所示。在将鼠标悬停在某个元素上时,我希望允许开发人员添加要发送到服务器的其他数据。我的想法是将getData()方法添加到我的插件中(注意,JSFIDLE示例没有这样做,因为它需要传递demoJSON对象来模拟ajax)。问题是此方法中的引用的是工具提示,而不是初始元素(即p.myElement),因此我无法访问与原始元素(即数据id)关联的数据。如

我组装了一个jQuery插件来查询服务器并显示工具提示弹出窗口。是的,我知道可能有更好的,但我一半的动机是自己学习如何这样做。现场演示位于,脚本如下所示。在将鼠标悬停在某个元素上时,我希望允许开发人员添加要发送到服务器的其他数据。我的想法是将getData()方法添加到我的插件中(注意,JSFIDLE示例没有这样做,因为它需要传递demoJSON对象来模拟ajax)。问题是
此方法中的
引用的是工具提示,而不是初始元素(即
p.myElement
),因此我无法访问与原始元素(即
数据id
)关联的数据。如何访问getData方法中的原始目标元素?如果我的总体方法不理想,请让我知道并推荐一个更好的方法,因为这是一个非常好的学习经验

作为一个非官方的问题,我如何防止悬停在元素右侧启动弹出窗口?我知道这可能更像是一个HTML问题,虽然我不希望得到答案,但我很乐意得到答案

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> 
        <title>screenshot</title>  
        <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script> 
        <script src="jquery.ajaxTip.js" type="text/javascript"></script> 
        <style type="text/css">

            .myElement{margin:100px;}
            .ajaxToolActive{color:blue;}

            .myAjaxTip {
                position:absolute;
                border:1px solid #CECECE;
                background:white;
                padding:10px;
                display:none;
                color:black;
                font-size:11px;-moz-border-radius:4px;
                box-shadow: 3px 1px 6px #505050;
                -khtml-border-radius:4px;
                -webkit-border-radius:4px;
                border-radius:4px;
            }
        </style> 

        <script type="text/javascript">
            $(function(){
                $('.myElement').ajaxTip({
                    display: function(d){return '<p>'+d.name+'</p><p>'+d.address+'</p><p>'+d.city+', '+d.state+'</p>';},
                    getData:function(){console.log(this);return {id:123}},
                    'class':'myAjaxTip'
                });
            });
        </script>
    </head>

    <body>
        <p class="myElement" data-id="1" title="ajaxTip Popup">John Doe</p>
        <p class="myElement" data-id="2" title="ajaxTip Popup">Jane Doe</p>
        <p class="myElement" data-id="3" title="ajaxTip Popup">Baby Doe</p>
    </body> 
</html> 


/*
* jQuery ajaxTip
* Copyright 2013 Michael Reed
* Dual licensed under the MIT and GPL licenses.
* 
* Notes
*/
(function( $ ){

    var methods = {
        init : function( options ) {
            // Create some defaults, extending them with any options that were provided
            var settings = $.extend({
                'url'      : 'getAjaxTip.php',        //To include extra data sent to the server, included it in the url
                'class'    : 'standardAjaxTip',
                'mouseMove': true,
                'delay'    : 250,   //miliseconds to delay before requesting data from server
                'xOffset'  : 20,
                'yOffset'  : 10,
                'dataType' : 'json',
                'getData'  : function(){return {}}, //Use to set additional data to the server
                'display'  : function(data){   //User function must include function(data) {... return string}
                    var string='';
                    for (var key in data) {string+='<p>'+data[key]+'</p>';}
                    return string;
                }
                }, options  || {});     //Just in case user doesn't provide options

            return this.each(function(){
                var showing,title,timeoutID,ajax,$t=$(this),ajaxTip;
                $t.hover(function(e) {
                    if(!showing){
                        title = this.title;this.title = "";//Prevent title from being displayed,and save for later to put back    
                        timeoutID=window.setTimeout(function() {
                            ajax=$.get( settings.url,settings.getData(),function(data){
                                ajaxTip=$('<div />').addClass(settings.class).html(((title != '')?'<h3>'+title+'</h3>':'')+settings.display(data))
                                .css("top",(e.pageY - settings.yOffset) + "px")
                                .css("left",(e.pageX + settings.xOffset) + "px")
                                .appendTo('body').fadeIn("fast");                    
                                showing = true;
                                $t.addClass('ajaxToolActive');
                                }, settings.dataType);
                            },settings.delay); //Delay before requesting data from server
                    }
                    },
                    function()
                    {
                        //When not hover
                        if (typeof ajax == 'object') {ajax.abort();}
                        window.clearTimeout(timeoutID);
                        this.title = title;    
                        $t.removeClass('ajaxToolActive');
                        if(showing){ajaxTip.remove();}
                        showing = false;
                });

                $t.mousemove(function(e) {
                    if(settings.mouseMove && showing) {ajaxTip.css("top",(e.pageY - settings.yOffset) + "px").css("left",(e.pageX + settings.xOffset) + "px");}
                });
            });
        },

        //Add additional methods as needed
        //destroy : function() {}

    };

    $.fn.ajaxTip = function(method) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.ajaxTip' );
        }    
    };


})( jQuery );

截图
.myElement{边距:100px;}
.ajaxToolActive{颜色:蓝色;}
myAjaxTip先生{
位置:绝对位置;
边框:1px实心#CECECE;
背景:白色;
填充:10px;
显示:无;
颜色:黑色;
字体大小:11px;-moz边框半径:4px;
盒影:3px 1px 6px#505050;
-khtml边界半径:4px;
-webkit边界半径:4px;
边界半径:4px;
}
$(函数(){
$('.myElement').ajaxTip({
显示:函数(d){return''+d.name+'

'+d.address+'

'+d.city+','+d.state+'

';}, getData:function(){console.log(this);返回{id:123}, “类”:“myAjaxTip” }); }); 约翰·多伊

简·多伊

婴儿Doe

/* *jQuery ajaxTip *版权所有2013迈克尔·里德 *MIT和GPL许可下的双重许可。 * *注释 */ (函数($){ var方法={ 初始化:函数(选项){ //创建一些默认值,使用提供的任何选项扩展它们 变量设置=$.extend({ 'url':'getAjaxTip.php',//要包含发送到服务器的额外数据,请将其包含在url中 “类”:“standardAjaxTip”, “mouseMove”:对, “延迟”:从服务器请求数据前延迟250,//毫秒 “xOffset”:20, “yOffset”:10, “数据类型”:“json”, 'getData':函数(){return{},//用于设置服务器的其他数据 “显示”:函数(数据){//用户函数必须包括函数(数据){…返回字符串} var字符串=“”; 对于(数据中的变量键){string+=''+data[key]+'

';} 返回字符串; } },options | |{});//以防用户不提供选项 返回此值。每个(函数(){ 变量显示,标题,timeoutID,ajax,$t=$(this),ajaxTip; $t.hover(功能(e){ 如果(!显示){ title=this.title;this.title=“”;//防止显示标题,并保存以备以后放回 timeoutID=window.setTimeout(函数(){ ajax=$.get(settings.url,settings.getData(),function(data){ ajaxTip=$('').addClass(settings.class).html(((title!='')?''+title+'':)+settings.display(数据)) .css(“顶部”(e.pageY-settings.yOffset)+“px”) .css(“左”(e.pageX+settings.xOffset)+“px”) .appendTo(“body”).fadeIn(“fast”); 显示=真实; $t.addClass('ajaxToolActive'); },设置。数据类型); },settings.delay);//从服务器请求数据之前的延迟 } }, 函数() { //不悬停时 if(typeof ajax=='object'){ajax.abort();} clearTimeout(timeoutID); this.title=标题; $t.removeClass('ajaxToolActive'); 如果(显示){ajaxTip.remove();} 显示=假; }); $t.mousemove(函数(e){ if(settings.mouseMove&&showing){ajaxTip.css(“top”,(e.pageY-settings.yOffset)+“px”).css(“left”,(e.pageX+settings.xOffset)+“px”);} }); }); }, //根据需要添加其他方法 //销毁:函数(){} }; $.fn.ajaxTip=函数(方法){ if(方法[方法]){ 返回方法[method].apply(this,Array.prototype.slice.call(arguments,1)); }else if(typeof方法=='object'| |!方法){ return methods.init.apply(这是参数); }否则{ $.error('Method'+Method+'在jQuery上不存在。
ajax=$.get( settings.url, settings.getData.call($t),function(data){
$('.myElement').ajaxTip({

    display: function(d){
        return '<p>'+d.name+'</p><p>'+d.address+'</p><p>'+d.city+', '+d.state+'</p>';
    },
    getData:function(){
       alert(this.data('id'));
    },
    'class':'myAjaxTip'
});