2013-04-02 23 views
1

我很難過。即使使用ON方法,jquery點擊事件也沒有結果

我創建了一個鏈接,彈出一個很好的窗體。

這裏的鏈接是什麼樣子:

<a class="buttonA right popForm" m="guest">form</a> 

在形式,它阿賈克斯的一個PHP頁面,除了所有其他的官樣文章,
它拉這兩更多相關線路:

<a class="buttonA right closeForm">X</a> 
<a class="test">test</a> 

這裏的jQuery:

$J(document).ready(function() { 
    $J(".popForm").click(function() { 
     var t = $J(this).attr("m"); 
     var id = ($J(this).attr("id") !== undefined ? $J(this).attr("id") : 0); 

     $J.ajax({ 
      beforeSend: function() { 
       //console.log(1); 
      }, 
      url: "popForm.php", 
      type: 'POST', 
      data: ({ 
       "t": t, 
       "id": id 
      }), 
      success: function (results) { 
       $J("#popup").html(results); 
       $J("#popup").show(); 
      } 
     }); 
    }); 
    $J(".test").on("click", function (e) { 
     console.log("e"+e); 
     alert('aa'); 
    }); 
    $J(".closeForm").on("click", function() { 
     alert(333); 
    }); 
}); 

現在我是前對我的「X」鏈接關閉窗體(或在這種情況下以333提醒我),
但鏈接已死亡。
其實,這兩個鏈接都是死的。

我所有,但跑出來的巧妙調試想法

  • 我運行的是最新的jQuery的lib
  • 我沒有的preventDefault在我的代碼的任何地方

回答

2

使用.on()但在delegated-events approach如:

$J("#popup").on("click", ".test", function (e) { 
    console.log("e"+e); 
    alert('aa'); 
}); 
$J("#popup").on("click", ".closeForm", function() { 
    alert(333); 
}); 

如果#popup在您點擊您的「調用彈出窗口」按鈕時沒有出現在DOM中 -
而不是#popup使用其他父元素!

http://api.jquery.com/on/#direct-and-delegated-events

委託事件有優勢,他們可以處理來自被添加到該文件在稍後的時間後代元素的事件。通過選擇在委託事件處理程序附加時保證存在的元素,可以使用委派事件來避免頻繁附加和刪除事件處理程序的需要。該元素可以是模型 - 視圖 - 控制器設計中的視圖的容器元素,例如,如果事件處理程序想要監視文檔中的所有冒泡事件,則可以是文檔。在加載任何其他HTML之前,文檔元素在文檔的頭部可用,因此在不等待文檔準備就緒的情況下在其中附加事件是安全的。

jQuery將不是像:

$J("#popup").on( // Ohh I know this guy it's in the DOModel! 
        // let's see what event bubbling will he listen for... 
    "click",  // hihi, I know this event! That event should descend from... 
    ".closeForm", // hm, there's no such fella yet, 
        // but if one day if I find him... 
    function() { // I'll show him what's a function!!! 
      alert(333); 
    } 
); 
+1

老兄你搖滾 - 是cuase我需要首先把父ELEM?我不能使用elem? – toy

+0

@toy如果之後從PHP生成'#popup',則應該是DOM準備好的頁面上已有的其他彈出框的父元素。或者,您可以使用'$(document)',但不建議聽到如此深的事件以鼓吹 –

+0

@toy - 如果我的答案對您有幫助(因爲您已收集其他3個問題),您會很樂意接受所有不被接受的答案! –