2010-05-06 20 views
6

मैं href पर एक jquery क्लिक ईवेंट जोड़ना चाहता हूं जिसमें पहले से ही एक ऑनक्लिक ईवेंट है। हार्ड कोडेड ऑनक्लिक ईवेंट के नीचे दिए गए उदाहरण में पहले ट्रिगर हो जाएगा। मैं इसे कैसे उलट सकता हूं?ऑनक्लिक घटनाओं का आदेश

<a class="whatever clickyGoal1" href="#" onclick="alert('trial game');">play trial</a> 
<br /> 
<a class="whatever clickyGoal2" href="#" onclick="alert('real game');">real trial</a> 
<p class="goal1"> 
</p> 
<p class="goal2"> 
</p> 

<script type="text/javascript"> 
    $("a.clickyGoal1").click(function() { 
     $("p.goal1").append("trial button click goal is fired");//example 
    }); 
    $("a.clickyGoal2").click(function() { 
     $("p.goal2").append("real button click goal is fired"); //example 
    });   
</script> 

उत्तर

6

आप, मूल ईवेंट हैंडलर मिल अपने स्वयं के साथ बदलें और फिर मूल हैंडलर कॉल करने के लिए की आवश्यकता होगी लेकिन मैं अगर है कि jQuery के साथ संभव है यकीन नहीं है।

// Wrapper in order not to add unnecceary variables to the global namespace 
(function(){ 
    var link = $("a.clickyGoal1")[0]; 
    var oldOnClick = link.onclick; 
    link.onclick = function(e) { 
    $("p.goal1").append("trial button click goal is fired"); 
    oldOnClick(e); 
    } 
})(); 
+0

और कभी-कभी यहां केवल तत्व तक पहुँचने के लिए और उसके बाद "सामान्य" जावास्क्रिप्ट हैंडलर स्थापित करने के लिए jQuery का उपयोग कर एक उदाहरण है , आपको पुराने फ़ंक्शन के अंदर 'this' चर को संरक्षित करने की आवश्यकता होगी, इसलिए समाधान 'oldOnClick.call (लिंक, ई)' करना है। – TautrimasPajarskas

1
$(function() { 
     $("a.whatever").removeAttr('onclick').click(function(e) { 
      e.preventDefault(); 
      var text = $(this).text(); 
      var cls = this.className.split(' ')[1].split('clickyGoal')[1]; 
      $('p.goal' + cls).fadeOut(500,function() { 
       $(this).html(text+' button fired '+cls).fadeIn(500,function() { 
        alert(text); 
       }); 
      }); 
     }); 
    }); 
संबंधित मुद्दे