jQuery中的“模板化” - 在选择器之间共享一些值

时间:2009-07-23 14:24:48

标签: jquery

另一个新手问题。我有一个关于creating a tooltip on focus的问题,这有效。解决方案让我想到这样的事情:

$("input[id$=tbMyTextbox]").qtip({
    content: 'Test',
    position: {
        corner: {
            target: 'rightMiddle',
            tooltip: 'leftMiddle'
        }
    },
    show: {
        when: {
            event: 'focus'
        }
    },
    hide: {
        when: {
            event: 'blur'
        }
    }
});

虽然这有效,但我需要实现许多工具提示,每次我只需要更改Selector和content-Attribute,而其他一切都是相同的。

jQuery中是否有通用的方法将设置放在一个公共位置?有点像子类化。

我对在循环中生成jQuery代码的任何服务器端解决方案都不感兴趣(由于a)一些技术限制和b)我学习jQuery的愿望。)

2 个答案:

答案 0 :(得分:1)

var defaultStyle =  {
    content: 'Test',
    position: { 
                corner: {
                            target: 'rightMiddle',
                            tooltip: 'leftMiddle'
                        }
                },
    show: { when: { event: 'focus' } },
    hide: { when: { event: 'blur' } }
}

//extend method will 'merge' defaultStyle with the second object that you have supplied, overriding properties in defaultStyle object if it exists in the second object. 

//myTextBoxStyle will have target as 'leftMiddle' and everything else from the default Style.
var myTextBoxStyle = $.extend(defaultStyle, { position : { corner { target : 'leftMiddle' } } });

$("input[id$=tbMyTextbox]").qtip(myTextBoxStyle);

答案 1 :(得分:1)

我这几天一直在使用qtip插件,我建议你将工具提示的内容存储在DOM元素的title属性中:

$("input[title]").qtip({ // All input elements that have a title attribute
    content: {
       text: false // Use each elements title attribute
    },
    position: {
        corner: {
            target: 'rightMiddle',
            tooltip: 'leftMiddle'
        }
    },
    show: {
        when: {
            event: 'focus'
        }
    },
    hide: {
        when: {
            event: 'blur'
        }
    }
});

...


<input type="text" title="My Tooltip"/>
<input type="checkbox" title="Another Tooltip"/>