使用JQuery函数减少重复的代码 [英] Reducing duplicated code with JQuery function

查看:85
本文介绍了使用JQuery函数减少重复的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里找到了一个不错的jquery弹出功能:

Found a good jquery popup function here:

 JAVASCRIPT
 $(function() {
    $("#word1234").live('click', function(event) {
        $(this).addClass("selected").parent().append('
          <div class="messagepop pop">"Lorem ipsum dolor sit amet, 
          consectetur adipisicing elit, sed do eiusmod tempor incididunt</div>');
        $(".pop").slideFadeToggle()
        $("#email").focus();
        return false;
    });
    $(".close").live('click', function() {
        $(".pop").slideFadeToggle();
        $("#contact").removeClass("selected");
        return false;
    });


 HTML
 <a href='/word1234' id='word1234'>Supercalifragilisticexpialidocious</a>

是否有更有效的调用此弹出窗口的方法?如果页面上有数百个定义,那么似乎不必要地重复了很多代码.

Is there a more efficient way of invoking this popup? If I have hundreds of definitions on a page I'd be repeating a lot of code seemingly unnecessarily.

如果我是在本机JS中执行此操作,则只需将一个onClick函数设置为href标记,例如

If I were doing this in native JS, I'd just set a onClick function to the href tag,something like

 <a href="#" id="word1234" onClick="doPop(this, 'Lorem ipsum, ect.')">Supercalifragilisticexpialidocious</a>

在JQuery中是否有类似的方法来调用函数?

Is there a similar method of calling a function in JQuery?

编辑 经过一些调试后,可以在这里找到更新/修复的脚本的工作版本: http://jsfiddle.net/N4QCZ/13/ hth.

EDIT After some debugging, a working version of the updated/fixed script can be found here: http://jsfiddle.net/N4QCZ/13/ hth.

推荐答案

您可以将代码转换为 jQuery插件是这样的:

You could turn the code into a jQuery Plugin like this:

$.fn.myPopup = function(popupText){
    var popupHtml = '<div class="messagepop pop">' + popupText + '</div>';
    this.each(function(){
        $(this).click(function(){

            // Create the popup
            $(this).addClass("selected").parent().append(popupHtml);

            // Find the close button and attach click handler
            $(this).find(".close").click(
                // Find, hide, then delete the popup
                $(this).closest(".pop").slideFadeToggle().remove();;
            );

        });
        return false;
    });

    return this;
};

然后您的代码将如下所示:

Then your code would look like this:

$("#word1234").myPopup("Lorem Ipsum");
$("#wordABCD").myPopup("Hello World");

这篇关于使用JQuery函数减少重复的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆