简体   繁体   中英

jQuery - trigger a custom event on a link

I am trying to run this custom 'getOffer()' event using jQuery

<a href="javascript: void getOffer();" title="Submit for offer"><img src="images/img.jpeg"></a>

I have tried the following but it doesn't seem to work (I am using the Firefox Firebug console.log window)

$('a[title="Submit for offer"]').trigger('getOffer');

This is the page I am trying this on: http://bit.ly/1dpIMFk Can anyone suggest any ideas?

 <a href="javascript: void getOffer();" title="Submit for offer"><img src="images/img.jpeg"></a>

$(document).ready(function(){
  $('a[title="Submit for offer"]').trigger('getOffer');
});

function getOffer(){
alert('link clicked');
}

Seems working fine for me.I think you didnt wrapped your event trigger in document ready. DEMO

您可以使用

<a href="#" onClick="getOffer();"><img src="images/img.jpeg"></a>

Creating an custom event on jQuery

First add some identifier (id/class) to your link

<a id="linkOffer" title="Submit for offer"><img src="images/img.jpeg"></a>

Then, create your CUSTOM event.

//The function that will to the getOffer things
function getOffer() {
    //Do get offer...  
}

$(document).ready(function(){

    //Custom event pointing to the function
    $('a#linkOffer').on('getoffer',getOffer);

    //Default click event
    $('a#linkOffer').on('click',function(e){
         //Do click stuff.

         //Trigger your custom event.
         $(this).trigger('getoffer');

         //If you wish to not move the page, prevent the default link click behavior (moveing to other page)
         e.preventDefault();
    });
});

Trigger will not function because it search click attribute in element. Work around for this can be is:

Add click attribute to the element and then call the jquery function.

<a href="javascript: void getOffer();" title="Submit for offer"></a>
    <button value="yu" onclick="getOffer();"/>
<script>

 $("a[title='Submit for offer']").attr("onclick",$("a[title='Submit for offer']").attr('href')); // get value from href
 $("a[title='Submit for offer']").trigger('click');  


 function getOffer()
 {
     alert('j');
 }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM