javascript - 如何创建 'JQuery' 函数调用并将数据传递给它们?

标签 javascript jquery

我正在使用 qtip jquery 插件添加工具提示。我可能会在整个网站上添加 50-60 个工具提示。

我现在发现的方法是一遍又一遍地剪切/粘贴 jquery 代码。例如:

// First, setup a tool tip for 'Enter Username'.
$("input#user_login").qtip({
   content: 'Enter username',
   position: {
     corner: {
       target: 'rightMiddle',
       tooltip: 'leftMiddle'
     }
   },
   style: { 
     border: {
       width: 1,
       radius: 3,
       color: '#0066CC'
    },
    width: 200,
    name: 'blue'
  }   
});

现在,重复“名字”的所有内容。看起来毫无意义。

$("input#user_login").qtip({
   content: 'Enter First Name',
   position: {
     corner: {
       target: 'rightMiddle',
       tooltip: 'leftMiddle'
     }
   },
   style: { 
     border: {
       width: 1,
       radius: 3,
       color: '#0066CC'
    },
    width: 200,
    name: 'blue'
  }  
});

如何创建一个可以将显示文本传递给其中的函数?

最佳答案

作为通用解决方案,任何时候您想使用默认选项然后扩展它,您都可以使用 $.extend()就这样:

var qtip_options = {
   content: 'I'm a tooltip,
   position: {
     corner: {
       target: 'rightMiddle',
       tooltip: 'leftMiddle'
     }
   },
   style: { 
     border: {
       width: 1,
       radius: 3,
       color: '#0066CC'
    },
    width: 200,
    name: 'blue'
  }   
};

$("#user_login").qtip($.extend({}, qtip_options, { content: 'Enter username'});
$("#first_name").qtip($.extend({}, qtip_options, { content: 'Enter First Name'});
<小时/>

或者在您的情况下,因为您经常这样做,让我们使用一个插件,如下所示:

$.fn.myQtip = function(text) {
  return this.qtip($.extend({}, qtip_options, { content: text});
};

然后就这样调用它:

$("#user_login").myQtip('Enter username');
$("#first_name").myQtip('Enter First Name');

关于javascript - 如何创建 'JQuery' 函数调用并将数据传递给它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4137807/

相关文章:

javascript - 查找数组中最大重复数的总和javascript

javascript - xml 文件中的导航问题

javascript - jQuery append 跳过空格后的内容

javascript - 缺乏使用 jQuery 的 li 元素的平滑展开折叠

javascript - Microsoft Edge 刷新按钮不执行 onLoad javascript 代码

PHP Session 和 JavaScript window.location.replace

javascript - YouTube API 和 Websockets 确保两个视频同步(视频 1 在视频 2 缓冲时暂停)

循环内的 JavaScript 闭包——简单实用的例子

javascript - 从 .css 移动到 jQuery css(),在动态添加元素时不起作用

javascript - 添加到网站时脚本不工作(在控制台中工作)