2013-02-12 67 views
4

找到了一個很好的jQuery彈出功能在這裏:減少重複的代碼與jQuery功能

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> 

有沒有調用這個彈出的更有效的方法?如果我在頁面上有數百個定義,我會看起來不必要地重複大量代碼。

如果我在本地JS這樣做,我只是設置的onClick功能的href標記,像

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

是否有類似的呼籲在JQuery中的函數的方法是什麼?

編輯 一些調試後,更新/固定腳本的工作版本可以在這裏找到:http://jsfiddle.net/N4QCZ/13/心連心。

+0

,而不是一個ID,這限制了您在單個DOM元素,使用一個類,它可以應用於任意多個dom元素。 – 2013-02-12 16:21:59

+0

如何定義彈出內容和元素之間的關係? – 2013-02-12 16:22:02

+0

在我自己的彈出庫中,添加彈出窗口的方法之一是有一個屬性:''. It's easy with jQuery to select elements with the attribute : '$('[bubble]')'. – 2013-02-12 16:23:42

回答

2

你可以轉碼成jQuery Plugin這樣的:

$.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; 
}; 

那麼你的代碼應該是這樣的:

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

彈出文本在所有單詞中都是相同的:「Lorem ipsum」。 – 2013-02-12 16:39:36

+0

我可以在JQuery中做到這一點? $(「#word1234」)。myPopup('Lorem ipsump,ect');如果這樣問題解決了。 – 2013-02-12 16:41:24

+0

是的,你可以做到這一點。我更新了代碼以反映這一點。 – KevSheedy 2013-02-12 16:45:54

1

不要使用live使用on,現場已被廢棄爲1.7:

你可以給你的鏈接彈出一個類,做:

$(".popup").on("click", function() { 
    // Your code 
}); 

這樣,你可以捕捉的所有鏈接popup類,而不是綁定到100事件的,即:

$("#id1").click() { } 
$("#id2").click() { } 

+0

This makes sense, but I need the id for removeClass(). – 2013-02-12 16:26:13

+0

Could do the same with the word definition? Supercali Jquery是否足夠聰明以在同一元素中繪製關聯? – 2013-02-12 16:31:24